필터 지우기
필터 지우기

how can I find the rows with l non zero elements in a matrix? (vital)

조회 수: 51 (최근 30일)
Homayoon
Homayoon 2015년 2월 19일
댓글: Souarv De 2023년 5월 23일
Hello, I will be so thankful of anyone who can help me with finding the answer? For example: Assume you have matrix r which is a n*m matrix as:
[ 0 0 0 0 0 6
1 0 1 0 0 0
3 0 0 0 0 0
0 0 0 0 0 0
2 3 0 0 0 0
0 0 0 0 0 0 ]
I want to find the rows with one nonzero element ( reported as a vector ) , two nonzero elements and so on. I know that to find the rows with zero elements, we can use the following code: ( Actually have learnt it recently )
s = find(all(r == 0, 2))
but I do not know if it is possible to do the same thing for rows with one or more nonzero elements or not. If so please help me to find the answer. So briefly speaking I am looking for the solution like :
[1
3]
for rows with one nonzero elements for the above example. I really do appreciate your helps. Thanks you. Homayoon

채택된 답변

Geoff Hayes
Geoff Hayes 2015년 2월 19일
Homayoon - you could do something similar to what you have already shown but look for those elements of r that are non-zero. We can use find to return the row index of each element that matches our criteria. If we assume that r is defined as above, then we can do
[rowIdcs, colIdcs] = find(r~=0);
where rowIdcs is
rowIdcs =
2
3
5
5
2
1
which tells us exactly how many elements of each row are non-zero. We can then use hist to summarize the above information
[counts, bins] = hist(rowIdcs,1:size(r,1));
where
counts =
1 2 1 0 2 0
bins =
1 2 3 4 5 6
So that we know which row (bin) has how many elements (count). With the above, you now know which rows have one, two, or three elements and
bins(counts==1)
returns
ans =
1 3
as expected. The three lines of code to get what you want would then be
[rowIdcs, ~] = find(r~=0);
[counts, bins] = hist(rowIdcs,1:size(r,1));
bins(counts==1)

추가 답변 (1개)

A. Sawas
A. Sawas 2018년 1월 12일
You can do it this way:
q = r > 0;
find(sum(q,2)==1)
you can replace the 1 with any count you want of the number of non-zero elements in a row.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by