Calling up automatically created matrix i in matlab

1 view (last 30 days)
Hi All,
I have a situation where I have created a matrix A(1) to A(n), also B(1) to B(n).
I used the following to create these matrices:
tmpl='A';
for i=1:n
m=sprintf('%s%2.3d=%insert function;',tmpl,i);
eval(m)
end
NOTE: so, A1 to An is created. If there is a better way of doing this, please advise...
The next step is where I need to multiply these matrices in a loop, see example:
for i=1:n
C(i) = B(i)*A(i)
end
NOTE: All the matrices are the same size.
so, basically if anyone can help and explain how to call up a matrix that was created automatically according to the value of i=1 to n I think I will be able to continue.
NOTE: If there is a better way of doing the same thing, please do tell.
Much appreciated,
G.D

Accepted Answer

Jan
Jan on 16 Sep 2013
Edited: Jan on 16 Sep 2013
This is a really, really bad idea. The automagic creation of variables is hard to read, in consequence hard to debug and in reduces the processing speed massively.
Use A{1}, A{2}, ... instead
or in your case A(:, :, i) would be working also.
  3 Comments
Walter Roberson
Walter Roberson on 18 Jul 2015
Please read the link that Jan provided... and please do not create your variables that way.
B = mat2cell(A,ones(1,size(A,1)), size(A,2));
C = cellfun(@(v) v(v~=0), B, 'Uniform', 0);
Image Analyst
Image Analyst on 19 Jul 2015
GD's "Answer" moved here. I also "Accepted" Jan's Answer for GD since GD said Jan's answer worked perfectly:
Works perfectly!!!!!!
Thanks! GD

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!