fprintf with 2d array in matlab

To use fprintf() with a 2D array in MATLAB, you can use nested for loops to iterate over the rows and columns of the array and print each element to a file. Here's an example code snippet that writes a 2D array to a file called "output.txt":

main.m
data = [1 2 3; 4 5 6; 7 8 9];  % example 2D array
filename = 'output.txt';  % output file name
fid = fopen(filename, 'w');  % open file for writing

% loop over rows and columns of the array and print each element to the file
for i = 1:size(data, 1)
    for j = 1:size(data, 2)
        fprintf(fid, '%d ', data(i,j));
    end
    fprintf(fid, '\n');  % print new line character after each row
end

fclose(fid);  % close the file
429 chars
14 lines

This will write the 2D array data to a file called "output.txt" in row-major order, with each row of the array on a separate line. The %d format specifier in the fprintf() call is used to print integer values. You can modify this to use other format specifiers, such as %f for floating-point values, depending on the data in your array.

gistlibby LogSnag