148 views (last 30 days)

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
on 19 Feb 2015

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)

A. Sawas
on 12 Jan 2018

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.

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.