Using arrayfun problem

3 次查看(过去 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 中查找有关 Outputs 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by