Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vectorized if in matlab

I have a boolean array call it flag.

I have two numeric arrays ifTrue, ifFalse. All these arrays are the same size, For purposes of this question assume every element in these arrays is unique.

I would like a function g with the property that

a = g(flag, ifTrue, ifFalse)

all(flag == (a == ifTrue))
all(~flag == (a == ifFalse))

Or in English, I would like g to return ifTrue elements when flag is true, and ifFalse elements when flag is false.

Or, in matlab, I could do this with loops:

a = zeros(size(ifTrue));
for i = 1 : numel(ifTrue);
    if flag(i)
         a(i) = ifTrue(i)
    else
         a(i) = ifFalse(i)
    end
end

Is there a vectorized approach?

Thanks

like image 734
John Avatar asked Dec 14 '11 14:12

John


2 Answers

%# Given, for example:
ifTrue = 1:10
ifFalse = -ifTrue  
flag = rand(1,10) > 0.5
%# First, set 'a' to ifFalse
a = ifFalse
%# Then override the places where flag is true
a(flag) = ifTrue(flag)
like image 157
Edric Avatar answered Sep 22 '22 17:09

Edric


Assuming that flag contains ones for true, and zeros for false elements: a = flag .* ifTrue + (1 - flag) .* ifFalse;

like image 24
kol Avatar answered Sep 21 '22 17:09

kol