Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical mask in Matlab

Tags:

matlab

I am trying to use a logical array mask to square all the values of this array a = [1:1:2000}. The logical array mask is defined as b = a <500. How would I square those values using the mask?

like image 572
someDude Avatar asked Dec 21 '22 19:12

someDude


2 Answers

a = 1:2000; %# 1 by 2000 double
b = a<500;  %# 1 by 2000 logical    
a_squared     = a(b).^2; %# 1 by 499 double
%# logical index--^ ^-- 'dot' means element-wise operation
like image 117
tmpearce Avatar answered Jan 05 '23 10:01

tmpearce


If you need the result to be the same size as a (keeping a >= 500 values as is), then:

a_sq = (a .^ 2) .* (a < 500) + a .* (a >= 500);
like image 37
Serg Avatar answered Jan 05 '23 09:01

Serg