MATLAB: How to write multiple numerical matrices to a csv file

write multiple matrices to a csv file

The matrices are 4 columns with uncertain rows (each matrix has 4 columns and different rows ), which are generated from a for loops. I want to write them to a csv file. The first matrix should be written starting from row 1 column 1, the second matrix starts from row 1, column 5. How should I do this?
Thanks, Eula

Best Answer

Comma-separated files with a different number of columns for the rows are unusual and many programs cannot handles them correctly. What should happen if the first matrix has less rows than the second one? Where should the corresponding rows start?
Therefore I recommend to choose another format. Or pad the missing elements with NaNs.
But f you really want to do this and the first matrix has more rows, try this:
A = rand(10, 4);
B = rand(5, 4);
nA = size(A, 1);
nB = size(B, 1);
C = cat(2, A(1:nB, :), B);
D = A(nB + 1:nA, :);
fid = fopen('YourFile.csv', 'w');
if fid == -1, error('Cannot open file for writing.'); end
fprintf('%g, %g, %g, %g, %g, %g, %g, %g\n', C');
fprintf('%g, %g, %g, %g\n', D');
fclose(fid);
Related Question