Saving/Working with variables using loop index?

1 view (last 30 days)
MRC
MRC on 15 Jan 2015
Answered: Geoff Hayes on 15 Jan 2015
Hi, I have some problems with the following piece of code in indexing the names using the loop index. Could you help me?
data1=[1,2,3];
data2=[4,5,6];
data3=[7,8,9]; %they are in the workspace
for h=1:3
% A`h'=data`h'+6
% save A`h' using a name depending on h
end
I can't use cells

Answers (1)

Geoff Hayes
Geoff Hayes on 15 Jan 2015
Cris - from your code it appears that you are trying to create a variable called A1 as
A1 = data1 + 6;
and do the same for A2 and A3. Is this the case? While you can do this using such functions as sprintf and eval, this isn't recommended because of the challenges in debugging the code when errors appear (among other reasons).
Instead, just create one matrix A which is built from the the three vectors, and then add 6 to it. Something like
A = [data1 ; data2 ; data3];
A = A +6;
Try the above and see what happens!

Community Treasure Hunt

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

Start Hunting!