Changing variable in a looped code

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,

 채택된 답변

Ilham Hardy
Ilham Hardy 2013년 9월 3일

0 개 추천

hint:
doc eval

댓글 수: 7

For this particular use (plotting), IMHO, i do not see the danger of utilizing eval. However i would like to be corrected.
for id = 1:3
eval(['plot(x' num2str(id) ',y)'])
hold all
end
Mazhar
Mazhar 2013년 9월 3일
Just read up the document about eval.
How exactly will I add this to my code above?
Ilham Hardy
Ilham Hardy 2013년 9월 3일
Just refresh your browser :P
Mazhar
Mazhar 2013년 9월 3일
Ah! Cheers :D
Ok I see how it works with the plot command. But now I'm trying to include it in to other calculations, for example
z = [4 1 3 4 5];
for k=1:3
distance = z - x;
distancesqr = distance' * distance;
end
again the for the first loop x1 is used and then x2 for the second loop and so on.
Ilham Hardy
Ilham Hardy 2013년 9월 3일
편집: Ilham Hardy 2013년 9월 3일
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)

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2013년 9월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by