Doug's MATLAB Video Tutorials

December 31st, 2009

Basics: Finding a subset of a matrix

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.

9 Responses to “Basics: Finding a subset of a matrix”

  1. matt fig replied on :

    Unless the vi is needed for something else, I usually forgo the find function in favor of logical indexing.

    vi = m(:,1) == target;

  2. Jimmy replied on :

    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.

  3. dhull replied on :

    @Jimmy,

    You can use

    [C,I] = min(…)

    C will be the value and I will be the index.

    Doug

  4. Rommy replied on :

    Hey doug

    Say if you have a 3×3 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?

  5. dhull replied on :
    >> a = magic(3)
    
    a =
    
         8     1     6
         3     5     7
         4     9     2
    
    >> vi = (a(:,1) == 3) & (a(:,3) == 7)
    
    vi =
    
         0
         1
         0
    
  6. Aparna replied on :

    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!

  7. dhull replied on :

    @Aparna,

    What do you mean you have submatrices? Are they stored in their own variable names? What is a label in MATLAB?

    Doug

  8. claire replied on :

    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?

  9. Doug replied on :

    @Claire,

    You can use two statements ((X<3) & (X>1))

    Doug

Leave a Reply

Wrap code fragments inside <pre> tags, like this:

<pre class="code">
a = magic(3);
sum(a)
</pre>

If you have a "<" character in your code, either follow it with a space or replace it with "&lt;" (including the semicolon).


MathWorks

Doug Hull is a proud MathWorker who is on a mission to help you with MATLAB.

Doug's picture

These postings are the author's and don't necessarily represent the opinions of The MathWorks.