Bird
0
0

You want to save a matrix to a file and then load it back in MATLAB. Which sequence of commands correctly achieves this?

hard📝 Application Q15 of 15
MATLAB - File I/O
You want to save a matrix to a file and then load it back in MATLAB. Which sequence of commands correctly achieves this?
AfileID = fopen('matrix.dat', 'w'); fwrite(fileID, matrix, 'double'); fclose(fileID); fileID = fopen('matrix.dat', 'r'); matrix2 = fread(fileID, [size(matrix,1), size(matrix,2)], 'double'); fclose(fileID);
Bfopen('matrix.dat', 'w'); fwrite(fileID, matrix); fclose(fileID); fileID = fopen('matrix.dat', 'r'); matrix2 = fread(fileID, [size(matrix,1), size(matrix,2)], 'double'); fclose(fileID);
CfileID = fopen('matrix.dat', 'r'); fwrite(fileID, matrix); fclose(fileID); fileID = fopen('matrix.dat', 'w'); matrix2 = fread(fileID); fclose(fileID);
DfileID = fopen('matrix.dat', 'w'); fwrite(matrix); fclose(fileID); fileID = fopen('matrix.dat', 'r'); matrix2 = fread(fileID); fclose(fileID);
Step-by-Step Solution
Solution:
  1. Step 1: Open file for writing and write matrix with type

    Open with fileID = fopen('matrix.dat', 'w'); then fwrite(fileID, matrix, 'double'); fclose(fileID). Specify data type 'double'.
  2. Step 2: Open file for reading and read matrix with size and type

    Open with fileID = fopen('matrix.dat', 'r'); then matrix2 = fread(fileID, [size(matrix,1), size(matrix,2)], 'double'); fclose(fileID).
  3. Final Answer:

    fileID = fopen('matrix.dat', 'w'); fwrite(fileID, matrix, 'double'); fclose(fileID); fileID = fopen('matrix.dat', 'r'); matrix2 = fread(fileID, [size(matrix,1), size(matrix,2)], 'double'); fclose(fileID); -> Option A
  4. Quick Check:

    Open-write-close, then open-read-close with types = correct [OK]
Quick Trick: Always specify fileID and data type when reading/writing matrices [OK]
Common Mistakes:
  • Not assigning fopen result to fileID
  • Using wrong file modes for reading/writing
  • Omitting data type in fwrite or fread
  • Calling fwrite without fileID

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More MATLAB Quizzes