필터 지우기
필터 지우기

Can I use a for loop in the condition statement of an if branch??

조회 수: 1 (최근 30일)
Teja Jupudi
Teja Jupudi 2014년 1월 7일
댓글: David Sanchez 2014년 1월 7일
I am trying to pick selected values of out one array and assign them to a new array. The condition for this 'picking' needs to have a for loop. I mean, the condition must be repeated for a given number of times. So, can I use a 'for' loop in the condition statement of the 'if'?? I have tried the other way round, where the 'if' comes inside 'for' and I have obtained erroneous results. If I am not allowed to do the above, kindly direct me as to how I could solve such an issue.

답변 (2개)

Simon
Simon 2014년 1월 7일
Can you give an example? As far as I understand you have some values in your array that must match some condition. You may write this without loops like
if (samplearray([1 4 6]) == [1 2 3])
...
end
  댓글 수: 3
Teja Jupudi
Teja Jupudi 2014년 1월 7일
I am sorry, I also have to tell you this:
I need the master array unaltered, value-wise and sequence wise. The values of the master array MAY be repeated. Values in the master array belonging to different categories may have the same value. So the only criteria to pick elements is to use the second array as a map.
Simon
Simon 2014년 1월 7일
Hi!
Just use a logical variable like
ConditionMet = true
for n = 1:NumberOfConditions
% check current condition
if ~(...)
ConditionMet = false
end
end
% now your if
if ConditionMet
...
else
...
end

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


David Sanchez
David Sanchez 2014년 1월 7일
No, you can not use a for-loop as the condition of an if statement as in the following WRONG code:
if (for k=1:3 k=k end)
disp('correct expression');
end
In case your if-statement needs more than one condition to be fulfilled, you have to use && to add them up.
if (1==1 && 2==2 && 3==3)
disp('correct expression');
end
  댓글 수: 2
Teja Jupudi
Teja Jupudi 2014년 1월 7일
I realized that. But the deal is, I need to verify the '&&' condition with an unknown number of values available only during run-time. Also the comparison of the condition variable is to be done with values that are obtained at run time.
If there is any other way to achieve said outcome, kindly share. Thanks!!
David Sanchez
David Sanchez 2014년 1월 7일
Sorry for the misunderstanding, can you provide some pseudo-code of what you need? I'm pretty sure you can do what you want but some code/pseudo-code would be of great help in order to give a more precise answer.

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by