Jane Lin
Jane Lin

Reputation: 21

How to count the number of 1's from the total matrix

I have code like below:

N=10;
R=[1 1 1 1 1 0 0 0 0 0;1 1 1 1 1 1 1 1 1 1];
p=[0.1,0.2,0.01];
B = zeros(N , N);
B(1:N,1:N) = eye(N);
C=[B;R];

for q=p(1:length(p))
    Rp=C;
    for i=1:N
        if(rand < p)
            Rp(i,:) = 0;
        end
    end
end

from this code I vary the value of p. So for different value of p, i am getting different Rp. Now I want to get the total number of "1"'s from each Rp matrix. it means may be for p1 I am getting Rp1=5, for p2, Rp=4.

For example

Rp1=[1 0 0 0 0;0 1 0 0 0;0 0 0 0 0],
Rp2=[1 0 0 0 0;0 1 0 0 0;1 0 0 0 0],
Rp3=[0 0 0 0 0;0 1 0 0 0;0 0 0 0 0],

So total result will be 2,3,1.

I want to get this result.

Upvotes: 2

Views: 413

Answers (3)

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

Assuming Rp is your matrix, then simply do one of the following:

If your matrix only contains zeros and ones

sum(Rp(:))

Or if your matrix contains multiple values:

sum(Rp(:)==1)

Note that for two dimensional matrices sum(Rp(:)) is the same as sum(sum(Rp))


I think your real question is how to save this result, you can do this by assigning it to an indexed varable, for example:

S(count) = sum(Rp(:));

This will require you to add a count variable that increases with one every step of the loop. It will be good practice (and efficient) to initialize your variable properly before the loop:

S = zeros(length(p),1);

Upvotes: 2

Mohsen Nosratinia
Mohsen Nosratinia

Reputation: 9864

If the matrix contains only 0 and 1 you are trying to count the nonzero values and there is a function for that called nnz

n = nnz(Rp);

As I mentioned in the comments you should replace

if(rand < p)

with

if(rand < q)

Then you can add the number of nonzero values to a vector like

r = [];
for q=p(1:length(p))
    Rp=C;
    for i=1:N
        if(rand < p)
            Rp(i,:) = 0;
        end
    end
    r = [r nnz(Rp)];
end

Then r will contain your desired result. There are many ways to improve your code as mentioned in other answers and comments.

Upvotes: 2

Will Faithfull
Will Faithfull

Reputation: 1908

If you need to count the 1's in any matrix M you should be able to do sum(M(:)==1)

Upvotes: 0

Related Questions