# Basics: Finding a subset of a matrix13

Posted by Doug Hull,

Imagine you have a matrix, and you want to make a subset of that matrix that has only the rows that have a 2 in the first column. This is how you would do that.

## 13 CommentsOldest to Newest

matt fig replied on : 1 of 13
Unless the vi is needed for something else, I usually forgo the find function in favor of logical indexing. vi = m(:,1) == target;
Jimmy replied on : 2 of 13
Hey doug, can this sort of approach be used to find the smallest value within a row or column of a matrix? if so how? Thanks.
dhull replied on : 3 of 13
@Jimmy, You can use [C,I] = min(...) C will be the value and I will be the index. Doug
Rommy replied on : 4 of 13
Hey doug Say if you have a 3x3 matrix and want to create a subset based on 2 key values, eg. column 1 must match value x and column column 2 must match y, and your index should only return rows where both criteria are true. Is this possible using the same simple approach?
dhull replied on : 5 of 13
>> a = magic(3)

a =

8     1     6
3     5     7
4     9     2

>> vi = (a(:,1) == 3) & (a(:,3) == 7)

vi =

0
1
0

Aparna replied on : 6 of 13
I have 5 sub matrices with labels 1-5. I am using a loop and i want to delete the ith label at each iteration. Anyone knows how to do it? c= mat2cell(exlData, count, cols+1); display (c); for i = 1 : k display (c{i,:}); end my matrix is stored in c{i,:} thanks!
dhull replied on : 7 of 13
@Aparna, What do you mean you have submatrices? Are they stored in their own variable names? What is a label in MATLAB? Doug
claire replied on : 8 of 13
Hi Doug Thanks for this, have found it to be really useful. Is there a way to target a range of values within the column? For example instead of returning all those that contain 2 in column 1, returning all those that contain 1, 2, and 3 in column 1?
Doug replied on : 9 of 13
@Claire, You can use two statements ((X<3) & (X>1)) Doug
Emily replied on : 10 of 13
Is there any built-in function can be called like: subset(matrix,[row vector], [column vector]), which performs the exactly same thing as matrix([row vector],[column vector])? Best Regards Emily
doug replied on : 11 of 13
Emily, Why would you want a function for this? What would it add?
pvsdtd replied on : 12 of 13
a=[1 10 2 20 3 30 4 40 5 50] b=[2 4] I want to have c matrix: c=[2 20 4 40] thank you!
Doug replied on : 13 of 13
>> a=[1 10 2 20 3 30 4 40 5 50] b=[2 4] a = 1 10 2 20 3 30 4 40 5 50 b = 2 4 >> c = a(b,:) c = 2 20 4 40

This site uses Akismet to reduce spam. Learn how your comment data is processed.