Name of an array with strcat and int2str. Simple task or not ?

Hi eveyone !
I'd like to change the name of an array containing an index evolving inside a loop. However, I'd wish to mention the value of the index in the very name of the array.
For instance, let's catch a glimpse at the following code :
a=[1 2 3; 4 5 6 ; 7 8 9];
b=zeros(3,3);
for i=1:3
z=strcat('b_',int2str(i));
z=b;
z(2,i)=a(1,i)
end
Instead of reading z(2,3)=3, I'd like to obtain b_1(2,1)=1, b_2(2,2)=2 , b_3(2,3)=3 . I'm also aware of the problem linked with the existence of an initialization inside the loop.
Could you give me any solutions to solve this question ?
Thanks.

 Accepted Answer

This is bad way - use many variables names:
a=[1 2 3; 4 5 6 ; 7 8 9];
b=zeros(3,3);
for i=1:3
eval(sprintf('b_%d = b;',i));
eval(sprintf('b_%d(2,%d) = a(1,%d);',i,i,i));
end
See Jan's answer

2 Comments

Thank you for your pieces of advice.
@Geoff: Did you read the FAQ?

Sign in to comment.

More Answers (1)

Don't do this. Use b{1}, b{2}, ... instead, because this is nicer, safer, faster and more flexible.
This topic is discussed frequently. And as all frequently appearing questions, it is mentioned in the FAQ: http://matlab.wikia.com/wiki/FAQ#How_can_I_create_variables_A1.2C_A2.2C....2CA10_in_a_loop.3F

Categories

Tags

Community Treasure Hunt

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

Start Hunting!