Effacer les filtres
Effacer les filtres

Extract some rows of the matrix with the find command

2 vues (au cours des 30 derniers jours)
Alberto Acri
Alberto Acri le 18 Août 2023
Modifié(e) : dpb le 19 Août 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];

Réponse acceptée

Dyuman Joshi
Dyuman Joshi le 18 Août 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

Plus de réponses (1)

dpb
dpb le 18 Août 2023
Modifié(e) : dpb le 19 Août 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
>>

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Tags

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by