How to call variables with consecutive names?
3 views (last 30 days)
Show older comments
Hello
If I have a number of variables with consecutive names e.g.
var1, var2, var3..., varn
and I want to do the same thing to all of them, how can I call them?
e.g.
for i = 1:n
do something to vari
end
I have tried
for i = 1:n
str = 'var%d';
data = sprintf(st,i);
do something to data
end
but this obviously give me data as a char variable and not the value of vari .
Thank you in advance!
0 Comments
Answers (1)
Adam
on 15 Mar 2015
Edited: Adam
on 15 Mar 2015
Don't do it. Just use an array. It is what they are for.
var(1), var(2), var(3), etc
or if you have different sized variables use a cell array:
var{1}, var{2}, var{3}, etc
Alternatively you can use a struct if you really want loads of field names as e.g
myStruct.( sprintf( 'var%d', 1 ) );
myStruct.( sprintf( 'var%d', 2 ) );
0 Comments
See Also
Categories
Find more on Variables 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!