From: Tamás Király on
hi! i have some code from which i'd like to eliminate the for loop, is it possible?

a=[2 4 5 6 7];
b=[3 5 8 2 6];
bool=[0 1 0 0 1];
result=ones(size(a))
for i=1:length(bool)
if bool(i)
result(i)=a(i);
else
result(i)=b(i);
end
end
%output: result=[3 4 8 2 7]
this is a simplification of my problem, the 'bool' is generated from a complex logic and 'a' and 'b' are not just numbers
so is there any solution to combine 2 matrix based on a bool vector?

thanks, Tamás
From: dpb on
Tamás Király wrote:
....

> a=[2 4 5 6 7];
> b=[3 5 8 2 6];
> bool=[0 1 0 0 1];
....

> %output: result=[3 4 8 2 7]
> this is a simplification of my problem, the 'bool' is generated from a
> complex logic and 'a' and 'b' are not just numbers
> so is there any solution to combine 2 matrix based on a bool vector?

l=logical(bool); % if it isn't actually already
b(l)=a(l);

--
From: Nathan on
On Apr 13, 5:08 pm, dpb <n...(a)non.net> wrote:
> Tamás Király wrote:
>
> ...
>
> > a=[2 4 5 6 7];
> > b=[3 5 8 2 6];
> > bool=[0 1 0 0 1];
>
> ...
>
> > %output: result=[3 4 8 2 7]
> > this is a simplification of my problem, the 'bool' is generated from a
> > complex logic and 'a' and 'b' are not just numbers
> > so is there any solution to combine 2 matrix based on a bool vector?
>
> l=logical(bool);  % if it isn't actually already
> b(l)=a(l);
>
> --

If he wants to keep the values in b, this is probably better:

l=logical(bool); % if it isn't actually already
result = b;
result(l) = a(l);


-Nathan
From: dpb on
Nathan wrote:
> On Apr 13, 5:08 pm, dpb <n...(a)non.net> wrote:
>> Tam�s Kir�ly wrote:
>>
>> ...
>>
>>> a=[2 4 5 6 7];
>>> b=[3 5 8 2 6];
>>> bool=[0 1 0 0 1];
>> ...
>>
>>> %output: result=[3 4 8 2 7]
>>> this is a simplification of my problem, the 'bool' is generated from a
>>> complex logic and 'a' and 'b' are not just numbers
>>> so is there any solution to combine 2 matrix based on a bool vector?
>> l=logical(bool); % if it isn't actually already
>> b(l)=a(l);
>>
>> --
>
> If he wants to keep the values in b, this is probably better:
>
> l=logical(bool); % if it isn't actually already
> result = b;
> result(l) = a(l);

Yes, as always, salt to suit...

--