Filter löschen
Filter löschen

Extract some rows of the matrix with the find command

2 Ansichten (letzte 30 Tage)
Alberto Acri
Alberto Acri am 18 Aug. 2023
Bearbeitet: dpb am 19 Aug. 2023
Hi. I would like to select rows from a 'matrix' array that have values between 0 and 2 in the third column of 'matrix'. I was able to select the desired rows but how can I combine them to create a unique matrix?
matrix = [6 6 5
7 6 0
8 6 10
9 6 3
10 6 7
11 6 0
12 6 2
13 6 0];
for k = 1:height(matrix)
for selected_number = 0:2
search = find(matrix(:,3) == selected_number);
select_row = matrix(search,:);
end
end
The output should be:
matrix_out = [7 6 0
11 6 0
12 6 2
13 6 0];

Akzeptierte Antwort

Dyuman Joshi
Dyuman Joshi am 18 Aug. 2023
Use ismember with logical indexing -
matrix = [6 6 5
7 6 0
8 6 10
9 6 3
10 6 7
11 6 0
12 6 2
13 6 0];
idx = ismember(matrix(:,3),0:2);
out = matrix(idx,:)
out = 4×3
7 6 0 11 6 0 12 6 2 13 6 0

Weitere Antworten (1)

dpb
dpb am 18 Aug. 2023
Bearbeitet: dpb am 19 Aug. 2023
Perfect application for a little utility function I keep around -- as a sidelight, I create and add to my MATLABPATH a "Utilities" folder that contains such tidbits as this; little tools that are handy but not built into base MATLAB distribution...
Very similar to @Dyuman Joshi's solution but not quite as expensive as ismember...
>> out=matrix(iswithin(matrix(:,3),0,2),:)
out =
7 6 0
11 6 0
12 6 2
13 6 0
>>
where iswithin is the utility function to return the logical indexing array. This is an extremely handy construct to be able to throw the details of the comparison into a black box and just return the result even for simple cases like this; it's even more useful in cases with multiple conditions or the like.
>> type iswithin.m
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
>>

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by