Search code examples
stringmatlabmatrixcell

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?


Solution

  • 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)