Pergunta

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

Foi útil?

Solução

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

Outras dicas

It's a little unclear what you want, but it would seem to be:

T = table(a(:), strings(:));

Assuming I'm reading the documentation for table correctly.

Or, for a cell array:

C = [num2cell(a(:)) strings(:)];

If you want to obtain a char array:

    aux = num2str(a(:));
    aux = mat2cell(aux,ones(1,size(aux,1)),size(aux,2));
    T = cell2mat([aux strings(:)]);

The result is a 2D char array (leading spaces are introduced if needed):

    T =

    1s1
    2s2
    3s3
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top