From: David Cubero on
Hi, i am using a For loop but it is very time consuming, can you help me to use another one..

alfa = sqrt(It.*It+Qt.*Qt);
for r = 1:length(It)
if alfa(r) == 0
I2(r)=0;
Q2(r)=0;
else
I2(r)=It(r)./alfa(r);
Q2(r)=Qt(r)./alfa(r);
end
end

This is done to avoid the division between zero because we do not want a NAN

Thank you
From: Grzegorz Popek on
Hello,

Not sure if it is the fastest solution, but you can use built-in 'find' function to locate nonzero elements of alfa and calculate your expression only for those indices.
After that you find zero elements of alfa (by looking for which indices alfa is equal to 0) and for these you assign 0 values in your vectors.

alfa = sqrt(It.*It+Qt.*Qt);
[~,ind] = find(alfa)
I2(ind) = It(ind)./alfa(ind);
Q2(ind) = Qt(ind)./alfa(ind);
[~,ind] = find(alfa==0);
I2(ind) = 0;
Q2(ind) = 0;


Or you can just create them with 'zeros' function beforehand (to make sure they have good length, otherwise you might miss some values at the end) and then you only need to assign non-zero elements:

alfa = sqrt(It.*It+Qt.*Qt);
I2 = zeros(size(It));
Q2 = zeros(size(It));
[~,ind] = find(alfa)
I2(ind) = It(ind)./alfa(ind);
Q2(ind) = Qt(ind)./alfa(ind);
From: Steve Amphlett on
"Grzegorz Popek" <liljoe(a)o2.pl> wrote in message <i16qec$fbm$1(a)fred.mathworks.com>...
> Hello,
>
> Not sure if it is the fastest solution, but you can use built-in 'find' function to locate nonzero elements of alfa and calculate your expression only for those indices.
> After that you find zero elements of alfa (by looking for which indices alfa is equal to 0) and for these you assign 0 values in your vectors.
>
> alfa = sqrt(It.*It+Qt.*Qt);
> [~,ind] = find(alfa)
> I2(ind) = It(ind)./alfa(ind);
> Q2(ind) = Qt(ind)./alfa(ind);
> [~,ind] = find(alfa==0);
> I2(ind) = 0;
> Q2(ind) = 0;
>
>
> Or you can just create them with 'zeros' function beforehand (to make sure they have good length, otherwise you might miss some values at the end) and then you only need to assign non-zero elements:
>
> alfa = sqrt(It.*It+Qt.*Qt);
> I2 = zeros(size(It));
> Q2 = zeros(size(It));
> [~,ind] = find(alfa)
> I2(ind) = It(ind)./alfa(ind);
> Q2(ind) = Qt(ind)./alfa(ind);

Another option (from many) using logical indexing rather than find...

% Don't worry about zero divisors
I2 = It./alfa;
Q2 = Qt./alfa;

% Remove all results where alfa is zero (Infs and NaNs)
idx=~alfa;
I2(idx)=0;
Q2(idx)=0;