LibettenRadler
LibettenRadler

Reputation: 115

How to select Matrix elements with a filter-matrix

I have 2 martices of the same size. The first contains values and the second only elements of 0 and 1 (like boolean). I now want all elements of my first Matrix stored in an array where the second Matrix has a 1 at the same index.

Maybe an example makes that clear:

Matrix 1:

a b c

d e f

g h i

Matrix 2:

0 1 1

1 0 0

0 0 1

output: [b c d i]

I think this will work in two steps, but i cant get it to work.

Upvotes: 1

Views: 169

Answers (2)

Jonas
Jonas

Reputation: 74940

This will need two steps indeed.

%# transpose Matrix 1 because Matlab iterates by row first
matrix_1 = matrix_1';

%# read values (transpose M2 as well)
%# also transpose the result to get a row-vector
output = matrix_1(matrix_2')';

Note that this indexing operation only works if matrix_2 is logical. If it isn't, cast it by writing logical(matrix_2) instead.

Upvotes: 3

High Performance Mark
High Performance Mark

Reputation: 78364

If your arrays are a and b, with b the mask array, try

a(find(b))

This won't produce the output in the order in your question. If order is important resort to @Jonas' approach.

Upvotes: 2

Related Questions