Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store string matrix and write to a file?

I don't know if Matlab can do this, but I want to store some strings in a 4×3 matrix, each element in the matrix is a string.

test_string_01  test_string_02  test_string_03
test_string_04  test_string_05  test_string_06
test_string_07  test_string_08  test_string_09
test_string_10  test_string_11  test_string_12

Then, I want to write this matrix into a plain text file, either comma or space delimited.

test_string_01,test_string_02,test_string_03
test_string_04,test_string_05,test_string_06
test_string_07,test_string_08,test_string_09
test_string_10,test_string_11,test_string_12

Seems like matrix data type is not capable of storing strings. I looked at cell. I tried to use dlmwrite() or csvwrite(), but both of them only accept matrices. I also tried cell2mat() first, but in that way all letters in the strings are comma seperated, like

t,e,s,t,_,s,t,r,i,n,g,_,0,1,t,e,s,t,_,s,t,r,i,n,g,_,0,2,t,e,s,t,_,s,t,r,i,n,g,_,0,3

So is there any way to achieve this?

like image 393
zihaoyu Avatar asked Jan 23 '26 04:01

zihaoyu


2 Answers

It is possible to shorten yuk's solution a bit.

strings = {
'test_string_01','test_string_02','test_string_03'
'test_string_04','test_string_05','test_string_06'
'test_string_07','test_string_08','test_string_09'
'test_string_10','test_string_11','test_string_12'};

fid = fopen('output.txt','w');
fmtString = [repmat('%s\t',1,size(strings,2)-1),'%s\n'];
fprintf(fid,fmtString,strings{:});
fclose(fid);
like image 98
Jonas Avatar answered Jan 24 '26 17:01

Jonas


Cell array is the way to store strings.

I agree it's a pain to save strings into a text file, but you can do it with this code:

strings = {
'test_string_01','test_string_02','test_string_03'
'test_string_04','test_string_05','test_string_06'
'test_string_07','test_string_08','test_string_09'
'test_string_10','test_string_11','test_string_12'};

fid = fopen('output.txt','w');
for row = 1:size(strings,1)
    fprintf(fid, repmat('%s\t',1,size(strings,2)-1), strings{row,1:end-1});
    fprintf(fid, '%s\n', strings{row,end});
end
fclose(fid);

Substitute \t with , to get csv file.

You can also store cell array of strings into Excel file with XLSWRITE (requires COM interface, so it's on Windows only):

xlswrite('output.xls',strings)
like image 38
yuk Avatar answered Jan 24 '26 18:01

yuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!