필터 지우기
필터 지우기

Hello everyone, I want to restrict the domain of a vector to return it to a smaller data set. For example, X between 2 and 7

조회 수: 2 (최근 30일)
X = [ 1 2 3 4 5 6 7 8 9 10 ];

채택된 답변

dpb
dpb 2022년 8월 10일
Perfect use for my utility function iswithin
>> x=1:10;
>> x=x(iswithin(x,2,7))
x =
2 3 4 5 6 7
>>
where iswithin is
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's just "syntactic sugar" remove the logical expression out of the main code for legibility, but it's extremely handy for shortening multiple range selections or the like or using it in arguments to other functions instead of building temporaries.
Copy to an m-file named "iswithin.m" and place wherever on your MATLABPATH you keep such handy little goodies where they're available for everybody. I create a "Utilities" subdirectory and insert in second in line in my MATLABPATH behind my current working directory.

추가 답변 (2개)

Image Analyst
Image Analyst 2022년 8월 10일
Try this:
X = [ 1 2 3 4 5 6 7 8 9 10];
mask = X > 2 & X < 7; % Or X >=2 & X <= 7
X = X(mask)
X = 1×4
3 4 5 6

the cyclist
the cyclist 2022년 8월 10일
X = [ 1 2 3 4 5 6 7 8 9 10 ];
idxToKeep = (X>=2) & (X<=7);
Xkeep = X(idxToKeep)
Xkeep = 1×6
2 3 4 5 6 7
You can also do it all in one line, without the intermediate variable
Xkeep = X((X>=2)&(X<=7))
Xkeep = 1×6
2 3 4 5 6 7
or not define a new variable, if you don't need one
X = X((X>=2)&(X<=7))
X = 1×6
2 3 4 5 6 7

카테고리

Help CenterFile Exchange에서 Environment and Settings에 대해 자세히 알아보기

제품


릴리스

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by