Sam
Sam

Reputation: 949

save different matrix in loop for matlab

I have a loop which iterates 20 time and produce matrix "A". I want to use a command to produce the results as A_1, A_2,..., A_20. How I should this?

Thanks.

Upvotes: 0

Views: 3342

Answers (2)

High Performance Mark
High Performance Mark

Reputation: 78316

If you don't want to use cell arrays you might consider the following:

A = zeros(nrow,ncols,20)

which will create a matrix A of dimension nrow*ncol*20. Always allocate the space for a large matrix in advance, don't built it plane by plane inside a loop. And replace nrow and ncol with whatever you want. Then

for i = 1:20
    A(:,:,i) = ... stuff ...
end

and now you have a single 3D matrix called A.

Upvotes: 2

Acorbe
Acorbe

Reputation: 8391

There are many ways of doing what you need. The more effortless is probably

  save([MyOutput,int2str(i)], 'A'); %where i is your iteration index, 
                                    %thus you will have 20 different files.

or

  save(MyOutput, 'A','-append'); %which generates one file in which 
                                 %all your matrices are stored consequently.

But really there are million ways. Try to be more specific about what you need.


If you just need to use the matrices in your workspace you may consider using cells.

N = 20;
A_t = cell(N,1);

%in cycle
for ...
A_t(i) = {A};


Now your `A_t{i}` (note different parenthesis) is a cell containing your `A_i`.

Upvotes: 0

Related Questions