MATLAB Answers

will99
0

how can I write two matrix into the same csv file

Asked by will99
on 23 Mar 2019
Latest activity Edited by dpb
on 23 Mar 2019
Accepted Answer by dpb
I'm trying to write two matrix into csv file using writematrix I tried to speart them with line as divider in the file but I couldn't do that I just want them to be in the same file but add headline or something to indicate which one is matrix a and b
so the file will be something like this (or next to each other)
a
1 4 9
16 25 36
49 64 100
b
1 4 9
16 25 36
49 64 100
how can I do that with writematrix?
a = [ 11 12 13;
14 15 16;
17 18 20]
b= [ 1 4 9;
16 25 36;
49 64 100]
writematrix(a,'a.csv','Delimiter','tab');
writematrix(b,'a.csv','Delimiter','tab');

  0 Comments

Sign in to comment.

1 Answer

Answer by dpb
on 23 Mar 2019
Edited by dpb
on 23 Mar 2019
 Accepted Answer

There's nothing in the documentation for writematrix that should have led you to think you could possibly do what you're asking with it.
It writes a matrix to a text or spreadsheet file but nothing is mentioned about having any header information or other than a homogenous matrix as an input and there are no optional named arguments that provide a naming facility nor, even, the ability to append to a file.
To do what you wish to do precisely, you would first open a file using fopen returning a file handle, write the formatted text with fprintf followed by writing the array. There you could possible use csvwrite with the append option. Then, "rinse and repeat" for the second array and close the file.
Alternatively, since your two arrays are commensurate in size, you could convert to a table and then use writetable which will identify variables in the table by column.
If the intent/need is to just have a way to save/recover a set of variables form the workspace and not to have text files for visual inspection and editing or some similar purpose, then the simplest way is to use the builtin Matlab storage facility of a .mat file --
save ab.mat a b
...
load ab
You can see whos in the .mat file with whos
>> whos -file xy.mat
Name Size Bytes Class Attributes
x2 10000x1 80000 double
y2 10000x1 80000 double
>>
for an example just laying around here...

  0 Comments

Sign in to comment.