views:

285

answers:

3

Hi I have problem with matrix..

I have many .txt files with different number of rows but have the same number of column (1 column)

e.g. s1.txt = 1234 rows
     s2.txt = 1200 rows
     s2.txt = 1100 rows

I wanted to combine the three files. Since its have different rows .. when I write it to a new file I got this error = Index exceeds matrix dimensions.

How I can solved this problem? .

+2  A: 

You can combine three matrices simply by stacking them: Assuming that s1, etc are the matrices you read in, you can make a new one like this:

snew = [s1; s2; s3];

You could also use the [] style stacking without creating the new matrix variable if you only need to do it once.

Donnie
+1  A: 

You have provided far too little information for an accurate diagnosis of your problem. Perhaps you have loaded the data from your files into variables in your workspace. Perhaps s1 has 1 column and 1234 rows, etc. Then you can concatenate the variables into one column vector like this:

totalVector = [s1; s2; s3];

and write it out to a file with a save() statement.

Does that help ?

High Performance Mark
A: 

Let me make an assumption that this question is connecting with your another question, and you want to combine those matrices by columns, leaving empty values in columns with fewer data.

In this case this code should work:

BaseFile ='s';
n=3;
A = cell(1,n);
for k=1:n
    A{k} = dlmread([BaseFile num2str(k) '.txt']);
end

% create cell array with maximum number of rows and n number of columns
B = cell(max(cellfun(@numel,A)),n); 

% convert each matrix in A to cell array and store in B
for k=1:n
    B(1:numel(A{k}),k) = num2cell(A{k});
end

% save the data
xlswrite('output.txt',B)

The code assumes you have one column in each file, otherwise it will not work.

yuk

related questions