'For' loop for specified integers (more than one)

Hello, I know that we can use for loop for specified integers like : for v=[1 5 23 99]. But I want to have more than one variable. I have to calculate every iteration in the loop with given initial condition (x,y,a). For example for:[ (x=1,y=0,a=0.2),(x=2,y=1,a=2) ] etc. Can I write it somehow ?

답변 (2개)

KSSV
KSSV 2016년 5월 10일

0 개 추천

P = [1 0 0.2 ; 2 1 2 ] ;
for i = 1:size(P,1)
x = P(i,1) ; y = P(i,2) ; a = P(i,3) ;
end

댓글 수: 1

Stephen23
Stephen23 2016년 5월 10일
편집: Stephen23 2016년 5월 10일
Note that you should not use i for variable names, as this is the name of the inbuilt imaginary unit:
Ditto for j, size, length, etc, etc.
You can use which to check if variable names are already allocated.

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

Stephen23
Stephen23 2016년 5월 10일
편집: Stephen23 2016년 5월 10일

0 개 추천

The simplest solution is to use indexing:
X = [1,2,3]
Y = [0,1,2];
A = [0.2,2,20];
for k = 1:numel(A)
x = X(k)
y = Y(k)
a = A(k)
end

댓글 수: 5

Eirini Gk
Eirini Gk 2016년 5월 10일
what is numel ?
Eirini Gk
Eirini Gk 2016년 5월 10일
im not sure that i explain well. I have a function and I input (x,y,a etc) it calculate many things but it is not the problem. Now I want to calculate these things for more than one (actually 12) initial cond.(x,y,a) and compare them to a graph. So it is not convenient to run the function 12 times because I cant compare the results by hand. Thats why Im trying to find a wayx to calculate for these 12 in.cond. in the same function..So i thought that for loop will help.
Stephen23
Stephen23 2016년 5월 10일
편집: Stephen23 2016년 5월 10일
It would be easiest if you showed us the function, some example data, and what exactly you want to have at the output. Perhaps you could try something like this:
X = [1,2,3]
Y = [0,1,2];
A = [0.2,2,20];
out = cell(size(A));
for k = 1:numel(A)
x = X(k)
y = Y(k)
a = A(k)
out{k} = myFunction(x,y,a,...);
end
Eirini Gk
Eirini Gk 2016년 5월 10일
One quastion more because Im quite new user of Matlab. If I have a variable s=0 s=s+1 that gets bigger in every iteration if I 'print' a(s) would it appear a(1), a(2) etc. or not ? Thank u very much
Stephen23
Stephen23 2016년 5월 10일
@Eirini Gk: Yes, it is just basic indexing. You just have to keep in mind that MATLAB indexing (like is common in mathematics) starts from one, not zero.

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

카테고리

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

질문:

2016년 5월 10일

댓글:

2016년 5월 10일

Community Treasure Hunt

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

Start Hunting!

Translated by