fprintf 3 dimensional array in matlab

To fprintf a 3-dimensional array in MATLAB, we can use the following approach:

main.m
% Initialize a 3-dimensional array
A = rand(3,3,3);

% Open a file to write the output
fid = fopen('output.txt','w');

% Loop through each slice of the array and fprintf to the output file
for i=1:size(A,3)
    fprintf(fid, 'Slice %d:\n', i);
    fprintf(fid, '%f %f %f\n', A(:,:,i)');
end

% Close the output file
fclose(fid);
328 chars
15 lines

In this code:

  • A is a 3-dimensional array of size 3x3x3.
  • The fid variable is used to store the file identifier returned by the fopen() function.
  • The for loop iterates over each slice of the 3D array.
  • The first fprintf statement prints a header for each slice.
  • The second fprintf statement prints the slice data in a formatted way by transposing the slice with the ' operator and using the %f format specifier to print each element.
  • The fclose() function is used to close the output file.

This code will write the contents of the 3-dimensional array to a file named output.txt, with each slice of the array preceded by a header indicating the slice number.

gistlibby LogSnag