A compact “if” statement using “or” operator

조회 수: 1 (최근 30일)
Sim
Sim 2023년 6월 1일
댓글: Sim 2023년 6월 2일
A more compact way to write the “if” statement using “or” operator, than this one?
if i == 1 || i == 2 || i == 7 || i == 8 || i == 10
% ...
end
Something similar to this statement?
if i == [1 2 7 8 10]
% ...
end

채택된 답변

Dyuman Joshi
Dyuman Joshi 2023년 6월 1일
편집: Dyuman Joshi 2023년 6월 1일
Yes there is - ismember
vec = [1 2 7 8 10];
i = 4;
%Checks if elements in i are present in vec or not
ismember(i,vec)
ans = logical
0
if ismember(i,vec)
disp('if')
else
disp('else')
end
else
  댓글 수: 7
Dyuman Joshi
Dyuman Joshi 2023년 6월 1일
편집: Dyuman Joshi 2023년 6월 1일
It is interesting to note that anyEq() is the fastest for first element and the slowest for the last element, and there timings of any() and ismember() are similar.
Edit - In the Overview section of the FileEx submission, Jan mentions - "Best case (first element matches): 99.99% faster for 1e6 elements (Matlab 2011b/64, MSVC 2008)"
%From the above tests done by James Tursa
n_any = 4.766502e-04;
n_is = 8.393297e-04;
n_eq = 4.046598e-06;
1-n_eq/n_any
ans = 0.9915
1-n_eq/n_is
ans = 0.9952
And it still holds.
Sim
Sim 2023년 6월 2일
thanks to everyone, @Dyuman Joshi @Stephen23 @James Tursa @DGM, for your comments!

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by