0

I have a 2d matrix (A=80,42), I am trying to split it into (80,1) 42 times and save it with a different name. i.e.

M_n1, M_n2, M_n3, … etc (representing the number of column)

I tried

for i= 1:42
    M_n(i)=A(:,i)
end

it didn't work

How can I do that without overwrite the result and save each iteration in a file (.txt) ?

aurelius
  • 3,946
  • 7
  • 40
  • 73
Turki
  • 71
  • 1
  • 9
  • Related question: http://stackoverflow.com/questions/15438464/matlab-changing-the-name-of-a-matrix-with-each-iteration/. Does that help? – Pursuit Jul 02 '14 at 05:17

2 Answers2

0

You can use eval

for ii = 1:size(A,2)
    eval( sprintf( 'M_n%d = A(:,%d);', ii, ii ) );
    % now you have M_n? var for you to process
end

However, the use of eval is not recommanded, you might be better off using cell array

M_n = mat2cell( A, [size(A,1)], ones( 1, size(A,2) ) );

Now you have M_n a cell array with 42 cells one for each column of A.
You can access the ii-th column by M_n{ii}

Shai
  • 111,146
  • 38
  • 238
  • 371
  • Thanks all for your replies, Shai: If I want to print the 42 cells in 42 txt files (.txt), how can I do that ? – Turki Jul 02 '14 at 08:48
  • @Turki you can `dlmwrite` each of the `M_n{ii}` vectors. – Shai Jul 02 '14 at 08:49
  • I tried it inside the loop but with no luck, could you please write it in more details? Sorry about that – Turki Jul 02 '14 at 09:04
0

Generally, doing if you consider doing this kind of things: don't. It does not scale up well, and having them in one array is usually far more convenient.

As long as the results have the same shape, you can use a standard array, if not you can put each result in a cell array eg. :

results = cell(nTests,1)
result{1} = runTest(inputs{1})

or even

results = cellfun(@runTest,inputs,'UniformOutput',false); % where inputs is a cell array

And so on.

If you do want to write the numbers to a file at each iteration, you could do it without the names with csvwrite or the like (since you're only talking about 80 numbers a time).

Another option is using matfile, which lets you write directly to a variable in a .mat file. Consult help matfile for the specifics.

jpjacobs
  • 9,359
  • 36
  • 45