How to call variables with consecutive names?
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Adam
2015-3-15
编辑:Adam
2015-3-15
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 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!