Hi, I would like to vectorize the following loop, have tried generating indices and but so far been successful.
a = any 1D vector
N = some value
for i=1:length(a)
for j=(i+1):length(a)
if(a(i)-a(j) > N)
disp('Far');
end
end
end
Does anyone have any ideas on this ?

댓글 수: 2

Guillaume
Guillaume 2018년 1월 31일
The ability of vectorising loops depends solely on the do something. So if you don't tell us what it is, we can't answer your question.
Balkrishna Patankar
Balkrishna Patankar 2018년 1월 31일
Updated

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

답변 (1개)

Guillaume
Guillaume 2018년 1월 31일

0 개 추천

Your example is trivially vectorised:
%R2016b or later:
isgreater = (a - a.') > N;
%any version:
isgreater = bsxfun(@minus, a, a.') > N;
isgreater(r, c) is true (1) when a(r)-a(c) > N

댓글 수: 3

This is not giving the correct answer. For example, if I run the following program :
N=-2;
b=[1 1 1;2 2 2;3 3 3;4 4 4;5 5 5];
a=[1;2;3;4;5];
for i = 1:length(a)
for j = (i+1):length(a)
if(a(i)-a(j) > N)
disp('Far');
end
end
end
This displays Far 4 times which means there ought to be 4 1's in your matrix.
isgreater = (a - a.') > N;
Gives 19 ones.
Guillaume
Guillaume 2018년 2월 1일
편집: Guillaume 2018년 2월 1일
Indeed, my answer was equivalent to having the j loop starting at 1 instead of i+1. The upper triangle of that isgreater matrix is the exact equivalent of your loops, so:
isgreater = triu((a - a.') > N, 1)
Balkrishna Patankar
Balkrishna Patankar 2018년 2월 2일
Thanks this worked !

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2018년 1월 31일

댓글:

2018년 2월 2일

Community Treasure Hunt

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

Start Hunting!

Translated by