Using arrayfun problem

3 views (last 30 days)
jy tan
jy tan on 5 Dec 2011
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

Accepted Answer

Walter Roberson
Walter Roberson on 5 Dec 2011
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 Comments
jy tan
jy tan on 5 Dec 2011
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 on 5 Dec 2011
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.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!