Reputation: 63
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?
Upvotes: 4
Views: 5176
Reputation: 14098
Another one, more tricky. Here we apply logical mask to the power, which gets values 1 or 2.
a_sq = a .^ (2 - (a >= 500));
Upvotes: 1
Reputation: 14098
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);
Upvotes: 2
Reputation: 12683
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
Upvotes: 8