How to find elements of a vector falling between minimum and maximum of an other vector without loop.
古いコメントを表示
Dear Community,
is there other way, than a loop to find elements in a vector b falling between the minimum and the maximum of vector a?
Let's say:
a=(1:1:10);
b=[5.5 11];
for i=1:length(b)
if b(:,i)>min(a) && b(:,i)<max(a)
c(:,i)=1;
else
c(:,i)=0;
end
end
Thanks for your suggestions! lg
採用された回答
その他の回答 (3 件)
Yazan
2021 年 7 月 4 日
c = zeros(size(b));
c(b>min(a(:)) & b<max(a(:))) = 1;
2 件のコメント
Stephen23
2021 年 7 月 5 日
Simpler:
c = b>min(a(:)) & b<max(a(:))
Levente Gellért
2021 年 7 月 6 日
dpb
2021 年 7 月 4 日
>> iswithin(b,min(a),max(a))
ans =
1×2 logical array
1 0
>>
is a common-enough idiom I have a utility function for the purpose--
>> function flg=iswithin(x,lo,hi)
% returns T for values within range of input
% SYNTAX:
% [log] = iswithin(x,lo,hi)
% returns T for x between lo and hi values, inclusive
flg= (x>=lo) & (x<=hi);
end
It isn't any different than writing the logical expression in line except as a function it has the advantage of moving the test to a lower level that is often very helpful in writing concise, legible expressions at the user level.
a=(1:1:10);
b=[5.5 11];
[~,~,c]=histcounts([0,5.5,10,11],[min(a),max(a)+eps(max(a))])
カテゴリ
ヘルプ センター および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!