Use logical values to extract a matrix not a vector?

Hi all,
I have a matrix like this:
M =
6 2 9
7 2 3
9 3 10
10 9 4
6 3 2
and a logical array like this:
logi =
5×3 logical array
1 1 0
1 1 0
1 1 0
0 0 0
0 0 0
If I extract associated values from M using logi:
K>> ext = M(logi)
ext =
6
7
9
2
2
3
but what I want is actually
K>> ext
ext =
6 2
7 2
9 3
So is there a way to extract the values into a matrix using logical operators? Using reshape or whatever to reshape the vector into matrix is forbidden in my case.

4 comentarios

Guillaume
Guillaume el 18 de Jun. de 2018
Editada: Guillaume el 18 de Jun. de 2018
There's no generic way as in most cases it would not be possible to get a matrix. E.g. what would the output be if your logical array was
1 1 0
0 0 1
1 1 0
0 0 0
0 1 0
instead?
Why is reshape forbidden? What other functions are forbidden?
Xiaohan Du
Xiaohan Du el 18 de Jun. de 2018
then is it possible to have the corresponding value at logical 1 and 0 at logical 0, so the resulting matrix has the same size as original one?
Xiaohan Du
Xiaohan Du el 18 de Jun. de 2018
can it be done if reshape is not forbidden?
If your 2 matrices have the same size in the first place:
ext=M.*logi

Iniciar sesión para comentar.

Respuestas (3)

Guillaume
Guillaume el 18 de Jun. de 2018
This is going to break in all sort of interesting ways if your logical array wouldn't result in a square matrix. Detecting such situations is left as an exercise to the reader...
[r, c] = find(logi);
ext = M(unique(r), unique(c))
Star Strider
Star Strider el 18 de Jun. de 2018
This will work for this particular problem and perhaps for similar situations. It will not work generically:
A = M.*logi;
C = num2cell(A);
I = cellfun(@eq, C, num2cell(zeros(size(C))));
C(I) = {[]};
ext = cell2mat(C)
ext =
6 2
7 2
9 3

Categorías

Etiquetas

Preguntada:

el 18 de Jun. de 2018

Respondida:

el 4 de Nov. de 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by