views:

81

answers:

2

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?

+2  A: 

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)
yuk
@yuk: My solution was too long to put into a comment. If you update your solution, I'll delete my answer.
Jonas
@Jonas, thanks for the better code. It definitely deserved to be a separate answer. (As for me, I would accept yours.) Too bad for me, it was late yesterday.
yuk
+2  A: 

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);
Jonas