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.

 채택된 답변

Jan
Jan 2012년 5월 3일

1 개 추천

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;

추가 답변 (3개)

Andrei Bobrov
Andrei Bobrov 2012년 5월 3일

2 개 추천

out = B + sign(B - A).*A;
EDITED on Jan's comment
out = (B~=A).*B + sign(B - A).*A;

댓글 수: 1

Jan
Jan 2012년 5월 3일
+1. A general suggestion for sign() compared to "if A>B, else, end": Check if the A==B case is correct!

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

Wayne King
Wayne King 2012년 5월 3일

0 개 추천

A=[1 2 3 4 5]';
B=[4 5 6 2 1]';
C = [A B];
D = C(:,2)-C(:,1);
out = [sum(C(D>0,:),2); diff(C(D<=0,:),[],2)]
Muhammad Affandi
Muhammad Affandi 2012년 5월 3일

0 개 추천

thanks..thats great.. now i have so many alternatives..

카테고리

도움말 센터 및 File 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