Kareem Ergawy
Kareem Ergawy

Reputation: 677

Vectorize and separate find operation in Matlab

I will try to explain what I am seeking through an example.

Suppose I have an 3x4 2D matrix like this:

1 0 0 0
1 1 1 0
0 0 1 1

This is the matlab matrix that can be produced by:

x = [1 0 0 0; 1 1 1 0; 0 0 1 1]

Now if I execute a command like this:

[~, y] = find(x([1 2], :) == 1)

y would be a vector that contains the column indices in rows 1 and 2 that have a value of 1. Specifically, for this example:

y = [1 1 2 3]

However, what I wish to accomplish is to separate the nonzero columns in every element of the input array (here [1 2]) without having to iterate over the elements of this input array (in vectorized way).

So I wish to get an output like this:

y = [[1] [1 2 3]]

Not strictly in this format but in any separated form.

Upvotes: 3

Views: 134

Answers (1)

Daniel
Daniel

Reputation: 36710

If I understood your question right, you want to group it according to the row. Then maintain the row:

[r, y] = find(x([1 2], :) == 1)

Then you could use accumarray

y2 = accumarray(r,y,[max(r),1],@(x)({x}))

For your example it returns

y2 = {[1],[1 2 3]}

Upvotes: 4

Related Questions