MATLAB: Avoiding for loop

for loopif statement

Hi..
I really want to avoid for loop in my program because it takes longer time if the array is too big.
For example i have two arrays. Let say A and B
A=[1 2 3 4 5];
B=[4 5 6 2 1];
and the outcome array C should be like this C=[5 7 9 -2 -4]
what i did was:
for i=1:length(B)
if (B(i)>A(i))
C(i)=B(i)+A(i);
else
C(i)=B(i)-A(i);
end
end
p/s: actually my function is a bit different but the principle is same.

Best Answer

And another solution:
A = [1 2 3 4 5]';
B = [4 5 6 2 1]';
index = B > A;
C(index) = B(index) + A(index);
nindex = ~index;
C(nindex) = B(nindex) - A(nindex);
And another one:
f = 2 * (B > A) - 1;
C = B + f .* A;