Changing variable in a looped code
2 views (last 30 days)
Show older comments
Hi, I have been trying to figure this out for a while. It will help in many cases.
I have a set of variables as such;
x1 = [3 4 5 2 3];
x2 = [4 2 7 8 3];
x3 = [8 2 9 3 9];
y = [1 5 3 8 5];
I would like to write a looped program in which the x variable in use would change in each loop. for example,
for i=1:3
plot(x,y)
hold all
end
I would like the program to use x1 for the first loop and than x2 for the second loop and so on.
I have tried writing xi but that does not work.
Thanks,
0 Comments
Accepted Answer
Ilham Hardy
on 3 Sep 2013
hint:
doc eval
7 Comments
Ilham Hardy
on 3 Sep 2013
Edited: Ilham Hardy
on 3 Sep 2013
Then it is (for many reasons that will be described by another fellow member :D) discouraged using the eval.
If you have a possibility (and will) to change/adjust the x. Then it will better to transform x into cell array.
e.g.
x1 = [3 4 5 2 3];
x2 = [4 2 7 8 3];
x3 = [8 2 9 3 9];
x_all = {x1;x2;x3};
y = [1 5 3 8 5];
z = [4 1 3 4 5];
% pre-allocate
distancesqr=cell(1,3);
for id = 1:3
%eval(['plot(x' num2str(id) ',y)'])
figure(1)
plot(x_all{id},y)
hold all
distance = z - x_all{id};
distancesqr{id} = distance' * distance;
end
%bonus
figure(2)
plot(distancesqr{:},y)
More Answers (2)
rifat
on 3 Sep 2013
for i=1:3
string=['plot(x' num2str(i) ',y);'];
eval(string);
end
I think this will do
0 Comments
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!