Using arrayfun problem

조회 수: 2 (최근 30일)
jy tan
jy tan 2011년 12월 5일
Is it correct if i use the code like this:
Final Load=[0 4 4];
C=[4.4 4.4 4.4]
N=arrayfun(@(S) function1(S,C),FinalLoad);
while any(N~=[0 0 0])
%%test each array of FinalLoad >C(Node Broken),if true go through while
%%loop, need to go through the loop once, but no do while function in
%%matlab
end
function1.m
function [r] = function1(S,C)
if(S>C)
r =1;
else
r=0;
end

채택된 답변

Walter Roberson
Walter Roberson 2011년 12월 5일
The MATLAB equivalent of
do while(Condition) {Block}
is
while Condition
Block
end
The translation is pretty direct.
The MATLAB equivalent of
do {Block} while(Condition)
can be written in three ways, two of which are minor variants of each other:
1)
while true
Block
if Condition; continue; end
break;
end
2)
while true
Block
if ~(Condition); break; end
end
3)
continue_loop = Condition;
while continue_loop
Block
continue_loop = Condition;
end
Remember that you need to assign new values to at least one variable involved in the condition, or else you end up with a loop that either does not execute at all (if the condition starts false) or executes infinitely. This is true also in whatever language you are borrowing your notion of "do while" from.
Thus, you need to define a new value for N inside the loop, possibly with another call to arrayfun(). I cannot recommend new code, however, as you do not indicate any mechanism to update S or FinalLoad.
Note: the function1 that you show and the arrayfun, could be replaced trivially.
N = FinalLoad > C;
  댓글 수: 2
jy tan
jy tan 2011년 12월 5일
it's more about whether the function1 works as expected
Let's say for the above example,
N should be = [0 1 1]
Walter Roberson
Walter Roberson 2011년 12월 5일
No N should not be that. Your FinalLoad starts as [0 4 4] and your C starts as [4.4 4.4 4.4]. 0 < 4.4, 4 < 4.4, 4 < 4.4, so all three FinalLoad values have the same relationship to C, so the result of arrayfun applied to function1 will be either [1 1 1] or [0 0 0] (depending on whether you have S>C or S<C)
None of the values in the list [0 4 4] are greater than the broken node value 4.4, so according to your comments in your code, the loop should not execute.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Automated Driving Toolbox에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by