How to call variables with consecutive names?

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!

Antworten (1)

Adam
Adam am 15 Mär. 2015
Bearbeitet: Adam am 15 Mär. 2015

3 Stimmen

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 ) );

Kategorien

Mehr zu Variables finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 15 Mär. 2015

Bearbeitet:

am 15 Mär. 2015

Community Treasure Hunt

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

Start Hunting!

Translated by