If condition: "in each row of a matrix one element is zero and the other one is not zero"
조회 수: 3 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
채택된 답변
Voss
2022년 3월 29일
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
추가 답변 (2개)
Stephen23
2022년 3월 29일
편집: Stephen23
2022년 3월 29일
A = [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
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
A = [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
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
Arif Hoq
2022년 3월 29일
편집: Arif Hoq
2022년 3월 29일
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
댓글 수: 2
Voss
2022년 3월 29일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!