Search code examples
stringmatlabconcatenationcell-array

getting a cell array of string into a matrix or table Matlab


I'm gathering information from calculations performed on some data and stored into arrays. I also have some info about these data coming from a text file which now and then contains strings.

The strings from the text files got saved into a {} cell array of strings such as:

strings={'s1' 's2' 's3'};
a=[1 2 3]

What the strings and arrays contain is generated based on a few conditionals from the data present in the text file as well as some data I have in matlab through a loop doing things like that:

srings{e}=blablahFromSomewhere{e}
a(e)=otherNumericalBlahBlahFromSomwehre(e+6)

Ultimately I want to joint this into a table. I would normally do this:

T=[a(:) strings(:)]

But I'm facing the following error:

Error using horzcat
Dimensions of matrices being concatenated are not consistent.

Can anyone help? I don't really want to transform the strings into integers because the content of the string is handier to have in the output in running the analysis.

Thanks :)


Solution

  • Code

    strings={'s1' 's2' 's3'};
    a=[1 2 3];
    outputfile = 'output.txt';
    
    %%// Code to horziontally concatenate to result in a Nx2 cell array
    out = [num2cell(num2str(a,'%d')') strings']
    
    %%// Write to outputfile - Method 1
    out = out';
    fid = fopen(outputfile,'w');
    fprintf(fid, '%s\t%s\n', out{:});
    fclose(fid);
    
    %%// Write to outputfile - Method 2
    %%// Create a text file and clear it out of any content. This is needed, as otherwise
    %%// XLSREAD was initializing CSV files with weird characters
    %% dlmwrite(outputfile,'');
    
    %%// Write to CSV file using XLSREAD
    %xlswrite(outputfile,out)
    
    %%// Verify
    type(outputfile)
    

    Output

    out = 
    
        '1'    's1'
        '2'    's2'
        '3'    's3'
    
    
    1   s1
    2   s2
    3   s3