Name of an array with strcat and int2str. Simple task or not ?
1 view (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Andrei Bobrov
on 13 Jun 2012
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
More Answers (1)
Jan
on 13 Jun 2012
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
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!