2

I am getting frustrated with MATLAB when I tried to get the data back in matrix format. But every time i only get back the answer in a single column format. I will illustrate my question:

For example,

A = [1 -3 2;5 4 7;-8 1 3];

L = logical(mod(A,2))

L =

     1     1     0
     1     0     1
     0     1     1

now I have another set of matrix sample called B, C is the output I would like to see

B = [100 300 200;500 400 700;800 100 300];

C = B(L)

C =

     100
     500
     300
     100
     700
     300

I don't want it to remain as a single column. I wonder what I can do to make C returned to me in this matrix format?

C =

     100     300     0
     500     0       700
     0       100     300

Thanks a lot, guys!!!

Machavity
  • 30,841
  • 27
  • 92
  • 100

2 Answers2

3

Logical indexing will select only the elements from the matrix for which the logical matrix is true. Obviously this means it can't retain it's original shape, since the number of elements will change. There are a few ways of doing what you want to do; the most efficient is probably:

C = B;
C(~L) = 0;

This sets C to B, then sets every element of the matrix for which L is false to zero.

MrAzzaman
  • 4,734
  • 12
  • 25
  • Wow, it just works! I never thought of that alternative way of solving this problem. So indeed the technical restriction is there, but you are really quick and smart to get around the problem! Thanks again! – cheehan lim Nov 05 '14 at 03:50
  • perhaps it's better to set excluded elements to `NaN` rather than `0` (which could be a valid value in `B`) – Amro Nov 05 '14 at 03:53
3

Or you could start with a blank matrix and set the desired elements:

C = NaN(size(B),'like',B);  % or zeros(size(B),'like',B)
C(L) = B(L);
chappjc
  • 30,359
  • 6
  • 75
  • 132