Vectorized if in matlab

I have a boolean array calling its flag .

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

I need 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 return ifTrue elements when flag is true, and ifFalse 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

+6
source share
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) 
+8
source

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

+1
source

Source: https://habr.com/ru/post/903774/


All Articles