Eliminating part of arrays in matlab

Assume that we have a 100*4 array.

We also have a 100*1 array of 1 and 0. Assume there are n 1's.

We want to create a n*4 array from the 100*4 array, where we only include the columns for which the second array is a 1.

One way to do it is through a double for loop. Is there a simpler method?

So, We have

A = [ [ 332 44 33 22 33 55 33 211 .....
      [ 823 44 12 98 19 23 32 911 .....
      ....
      ....
    ]

and

 B = [1 0 0 1 0 0 0 ....]

and we want

 C = [ [ 332 22 ...
       [ 823 98 ...
       ....
       ....
     ]

Upvotes: 0

Views: 311

Answers (2)

Shai
Shai

Reputation: 114796

You should use logical indexing:

C = A(:, B==1 );

Upvotes: 4

ClojureMostly
ClojureMostly

Reputation: 4713

First you repmat the logical vector so that it has the exact same size as the matrix A.

idx2keep = repmat(b, [1 4]); % Or [4 1] depending on if it's a col or row vector

Then you can simply index them with

 B = A( idx2keep )

you can then make it into a column vector:

 B = B(:)

That should do the job. Next time please always post some code or notation so it's easier and clearer to answer this.

Upvotes: 1

Related Questions