0

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 ...
       ....
       ....
     ]
Shai
  • 111,146
  • 38
  • 238
  • 371
  • Have a look at [this question/answer](http://stackoverflow.com/questions/11419220/matlab-extract-submatrix-with-logical-indexing), I think you are looking for a form of logical indexing. – Schorsch Jun 20 '13 at 17:35

2 Answers2

4

You should use logical indexing:

C = A(:, B==1 );
Shai
  • 111,146
  • 38
  • 238
  • 371
1

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.

ClojureMostly
  • 4,652
  • 2
  • 22
  • 24