if statement for range of array values

Is there a better way to write this 'if' statement?
for i = 1:size(somevalue)
if (x(i) < xmax && x(i-1) < xmax && x(i-2) < xmax) || (y(i) < ymax && y(i-1) < ymax)
disp('do something');
end
Thanks for your help!

댓글 수: 1

Oleg Komarov
Oleg Komarov 2012년 5월 9일
Trivial question, do you want the condition to be verified on any (&&) of the 3 consecutive values or on all (&)?

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

답변 (3개)

Wayne King
Wayne King 2012년 5월 9일

3 개 추천

How about
if (any(x<xmax) || any(y<ymax))
disp('do something');
end
or do you really want to test if every one is? Of course it seems that x<xmax or y<ymax are to be always true.

댓글 수: 4

Sean de Wolski
Sean de Wolski 2012년 5월 9일
golf:
if any([x<k,y<p]);disp('do something');end
Sean de Wolski
Sean de Wolski 2012년 5월 9일
(assuming x,y are both row vectors)
Jan
Jan 2012년 5월 9일
@Sean: This needs to create a temporary array of the length numel(x)+numel(y). Therefore I assume this is slower than Wayne's approach.
Richard Brown
Richard Brown 2012년 5월 9일
Hence golf :)

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

Dr. Seis
Dr. Seis 2012년 5월 9일

0 개 추천

I think what you might be after is something like:
if all(x(i-1:i+1) < xmax) || all(y(i-1:i+1) < ymax)
% something
end

댓글 수: 2

Dr. Seis
Dr. Seis 2012년 5월 9일
Misinterpreted your "if" statement on my previous attempt. This should be what you are after.
Note: "all" will return TRUE if and only if the entire array returned from "x<xmax" is all 1's. "any" will return TRUE if there is one or more 1 in the array returned by "x<xmax".
Richard Brown
Richard Brown 2012년 5월 9일
If doing it this way, the x indices should be i-2:i, and the y indices should be i-1:i, and the loop should start at 3

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

Richard Brown
Richard Brown 2012년 5월 9일

0 개 추천

To check I've understood correctly, you only want to do something if the current and two preceding x values are all less than xmax, or, the current and preceding y values are both less than ymax. Then, the indices you are interested in are given by:
idx = find(filter([1 1 1], 1, x < xmax) == 3 | filter([1 1], 1, y < ymax) == 2)
Note that 1 and 2 will never appear in idx as your expression cannot be evaluated for these

카테고리

도움말 센터File Exchange에서 Variables에 대해 자세히 알아보기

태그

질문:

2012년 5월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by