Elementwise ifs in matlab - do they exist?

Let's say I have the following basic if statement:

if (A ~= 0)
   % do something like divide your favorite number by A
else
   % do something like return NaN or infinity
end

The problem is that A is not a prime, but a vector. Matlab returns true if no element in is 0. What I'm looking for is vectorized? way to punch the above if statement for each element in A.

Actually, I just want to do it as quickly as possible.

+3
source share
5 answers
B = zeros(size(A));
B(A~=0) = FAV./A(A~=0);  
B(A==0) = NaN;
+4
source

Vectorized ifs do not exist, but there are some options. If you want to test all or any elements of true, use all or any function.

Here is one example of conditionally changing matrix values:

b = A ~= 0;      % b is a boolean matrix pointing to nonzero indices
                 % (b could be derived from some other condition,
                 %  like b = sin(A)>0
A(b) = f(A(b))   % do something with the indices that pass
A(~b) = g(A(~b)) % do something else with the indices that fail
+6
source

:

Z = B .* X + ~B .* Y;

B - . ,

Z = (A == 0) .* -1 + (A ~= 0) .* A;

A, -1 , A .

, NaNs, :

Z = FAV ./ A; % produces inf where A == 0
Z = (A ~= 0) .* FAV ./ A; % produces NaN where A == 0
+1

? .

nonzero = find(A); % returns indicies to all non-zero elements of A
y = x./A(nonzero); % divides x by all non-zero elements of A
                   % y will be the same size as nonzero

,

y = x./A(A~=0); % divides x by all non-zero elements of A
0

, , . FIND. VI ( ) .

clear
clc

den = [2 0 2; 0 2 0; -2 -2 -2]
num = ones(size(den));
frac = nan(size(den));

vi = (den ~=0)

frac(vi) = num(vi)./den(vi)

vi = (den == 0)

frac(vi) = nan %just for good measure...
0

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


All Articles