How to make an if-statement that finds whether a 1x5 column has 4 of the rows the value 0?

조회 수: 1(최근 30일)
abbyeit
abbyeit 2021년 10월 12일
답변: Image Analyst 2021년 10월 12일
Hello,
I am currently wondering how I could make an if statement that finds out whether a 1x5 matrix has more than 4 of the indexes (right term?) more than 0.
E.g.
I have a randomized function where the 1x5 matrix can have random numbers, but sometimes it can happen that the matrix randomly generates:
matrix =
0
0
0
241
0
I want my code to do something in particular when there is more than 4 zeros with an if-statement, but have no idea how to formulate the if-statement.
Any help is appreciated!

채택된 답변

Mathieu NOE
Mathieu NOE 2021년 10월 12일
hello
my suggestion below :
matrix = [0 0 0 241 0];
ind1 = find(abs(matrix) == 0); % method 1 can be unpredictabe if value in data is almost but not truly zero
tol = eps; % a very small number
ind2 = find(abs(matrix)<tol); % method 2 ; much more robust against "almost" zero issue
if numel(ind2) > 4 % or whatever
% your code here
end

추가 답변(2개)

dpb
dpb 2021년 10월 12일
Just a somewhat pedantic comment on details of notation first -- If the matrix is 1x5, it would be
matrix = [0 0 0 241 0]
instead, a row vector, not column as given above. For addressing a vector it won't matter much, but is quite important to have orientation correct if were 2D instead and also for things like matrix multiplication, etc.
Anyways, tutorial aside, if the size is always 5 elements, then >4 elements being zero is equivalent to
if ~all(M)
...do something here
end
because >4 ==> 5 which is the full size of the vector.
Or if the size is variable or the criterion is for some number other than all, then use
sum(M==0)>=(numel(M)-n)
where n is the number of nonzero elements required (1 in the above case).

Image Analyst
Image Analyst 2021년 10월 12일
Well you've asked about two sort of opposite situations:
  1. "more than 4 zeros", and
  2. "more than 4 of the indexes more than 0"
So I give solutions for both situations below:
matrix = [0 0 0 241 0]
% Situation 1: "when there is more than 4 zeros"
% Method 1 to find where there are 4 or more zeros.
if nnz(~matrix) >= 4
% It has 4 or more zeros.
end
% Method 2 to find where there are 4 or more zeros.
if sum(matrix) >= 4
% It has 4 or more zeros.
end
% Situation 2 : "finds out whether a 1x5 matrix has more than 4 of the indexes more than 0."
if sum(matrix > 0) > 4
% It has more than 4 positive values ("more than 0").
end

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by