Logical arrays as indices to arrays to convert elements to zero in MATLAB

Multi tool use
Multi tool use


Logical arrays as indices to arrays to convert elements to zero in MATLAB



I am trying to convert some elements of a matrix to zeros depending on a logical array.



Suppose we have a random 5 x 5 matrix:


5 x 5


b =

0.0344 0.1869 0.7547 0.1190 0.2238
0.4387 0.4898 0.2760 0.4984 0.7513
0.3816 0.4456 0.6797 0.9597 0.2551
0.7655 0.6463 0.6551 0.3404 0.5060
0.7952 0.7094 0.1626 0.5853 0.6991



And I have an array of zeros and ones with the same dimension:


a =

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



Doing a(logical(b)) gives me the elements I am looking for, but in a vector form:


a(logical(b))


ans =

0.4387
0.3816
0.1869
0.4456
0.6463
0.7547
0.2760
0.6551
0.1626
0.4984
0.9597
0.5853
0.2551
0.5060



How can I get the following matrix instead?


0 0.1869 0.7547 0 0
0.4387 0 0.2760 0.4984 0.7513
0.3816 0.4456 0 0.9597 0.2551
0 0.6463 0.6551 0 0.5060
0 0 0.1626 0.5853 0




1 Answer
1



I just realized that there was an answer in another question.



Setting b(~logical(a)) = 0 works.


b(~logical(a)) = 0



(Just keeping this here because the question is phrased a bit differently.)





You can do b(a == 0) = 0; to be even shorter. I would say this more expressly states what you want to do rather than using ~logical(a).
– rayryeng
Apr 1 '15 at 0:15



b(a == 0) = 0;


~logical(a)





You could also do an element-wise multiply .*.
– knedlsepp
Apr 1 '15 at 0:20


.*






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

B37Wex4CNTD,E
mMaEg4m WJk3DQ1awcI rQeS 6i4Ja OJ

Popular posts from this blog

Rothschild family

Cinema of Italy