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!!!

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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!
perhaps it's better to set excluded elements to NaN rather than 0 (which could be a valid value in B)
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.