If condition: "in each row of a matrix one element is zero and the other one is not zero"

3 visualizaciones (últimos 30 días)
How can I write the
if condition
in a more compact way than
if size(find(sum(A==0,2)==1),1) == size(A,1)
to express that "in each row of my matrix one element is zero and the other one is not zero" ?
Here an example:
clc;
A = [ 1 0
0 9
12 0
0 2
0 3]
if size(find(sum(A==0,2)==1),1) == size(A,1)
disp('in each row one element is zero and the other one is not zero')
end

Respuesta aceptada

Voss
Voss el 29 de Mzo. de 2022
You can use all()
A = [ 1 0
0 9
12 0
0 2
0 3];
if all(sum(A==0,2) == 1)
disp('in each row one element is zero and the other one is not zero')
end
in each row one element is zero and the other one is not zero

Más respuestas (2)

Stephen23
Stephen23 el 29 de Mzo. de 2022
Editada: Stephen23 el 29 de Mzo. de 2022
A = [1,0;0,9;12,0;0,2;0,3]
A = 5×2
1 0 0 9 12 0 0 2 0 3
if any(A,2)&any(~A,2)
disp('in each row one element is zero and the other one is not zero')
end
in each row one element is zero and the other one is not zero
if diff(A==0,1,2) % this might be the most compact
disp('in each row one element is zero and the other one is not zero')
end
in each row one element is zero and the other one is not zero
A = [1,2;0,0;12,0;0,2;0,3]
A = 5×2
1 2 0 0 12 0 0 2 0 3
if any(A,2)&any(~A,2)
disp('in each row one element is zero and the other one is not zero')
else
disp('but not this one!')
end
but not this one!
if diff(A==0,1,2)
disp('in each row one element is zero and the other one is not zero')
else
disp('but not this one!')
end
but not this one!

Arif Hoq
Arif Hoq el 29 de Mzo. de 2022
Editada: Arif Hoq el 29 de Mzo. de 2022
try this
A = [ 1 0
0 9
12 0
0 2
0 3];
if nnz(A)==size(A,1)
disp('in each row one element is zero and the other one is not zero')
end
in each row one element is zero and the other one is not zero
  2 comentarios
Voss
Voss el 29 de Mzo. de 2022
This method doesn't take into account the number of zero and non-zero elements by row, only the total:
A = [ 1 2
0 0
12 0
0 2
0 3];
if nnz(A)==size(A,1)
disp('in each row one element is zero and the other one is not zero')
end
in each row one element is zero and the other one is not zero
Sim
Sim el 29 de Mzo. de 2022
Many thanks @Arif Hoq..! A very compact "if statement"! I would accept all the answers... !!

Iniciar sesión para comentar.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by