Little Bobby Tables
Little Bobby Tables

Reputation: 4744

How do I find multiple columns greater than a single column in MATLAB?

I have a single column vector that is an average of the other multiple columns (in a vector). I wish to index when each element of the matrix is is greater than the average vector. I am able to do this one at a time with:

idx = y1<y2

however if y2 is a matrix it comes up with an error. My current solution to over come this is:

y1 = [y1;y1]

but this is rather inelegant and doesn't account for y2's of unknown sizes. Regards

Upvotes: 1

Views: 62

Answers (2)

moink
moink

Reputation: 888

Try using the function repmat.

repmat(A,n1,n2) makes an n1 x n2 tiling of A.

So if you want to make a vector with n identical columns each containing y1 you can run:

repmat(y1,1,n)

The number of columns you want is the number of columns in y2, which is

size(y2,2)

Thus, the solution you are looking for is:

idx=y2>repmat(y1,1,size(y2,2))

Upvotes: 2

Divakar
Divakar

Reputation: 221554

I think you are looking for something like this -

idx = bsxfun(@lt,y1,y2)

This will create a logical array of the same size as the input matrix y2 with 1's where the elements in y2 are greater than the corresponding elements in y1 and 0's otherwise.

Best thing about bsxfun to solve such a problem is that it takes care of the expansion needed. So, what you would have is a generic solution without even querying for the sizes.

Upvotes: 7

Related Questions