Sum of the element occurence

Greetings Matlab Community,
I've manage to sum up the occurrence of number 2 of the entire matrix by using this,
chromo = [1 1 2 4 6 1 ; 2 1 3 5 7 2];
sum(chromo(:) == 2)
How do i sum up the occurrence of number 2 in just a row in the matrix and not the entire matrix?

 Risposta accettata

Ameer Hamza
Ameer Hamza il 29 Apr 2018
If A is the matrix, you can do this as follow
numOfTwos = sum(A==2, 2);
myResult = numOfTwos(rowNumber);
The above will numOfTwos will give number fo two in all the rows of matrix A. If you just want it for one row, use
numOfTwos = sum(A(rowNumber, :) ==2, 2);

7 Commenti

yiwen yim
yiwen yim il 29 Apr 2018
Thank you for you reply. However, every time i try to run with rowNumber in the code it will gives this error,
'Undefined function or variable 'rowNumber'.'
Please explain further.
You need to define rowNumber before running the code. For example in the beginning run
rowNumber = 3;
In your question you asked "How do i sum up the occurrence of number 2 in just a row in the matrix". Did you mean how to do it for one particular row? Or is the question about how to do it for each row ?
Ameer Hamza
Ameer Hamza il 29 Apr 2018
@yiwen yim answer moved here
"I would like to know how to do it for each row."
this line will tell the number of 2's in each row of A
numOfTwos = sum(A==2, 2);
Ameer Hamza
Ameer Hamza il 29 Apr 2018
@yiwen yim answer moved here
"Also for a particular row."
For particular row you can do this
numOfTwos = sum(A(3, :) ==2, 2);
It will tell you number of twos in row 3.

Accedi per commentare.

Più risposte (2)

yiwen yim
yiwen yim il 29 Apr 2018

0 voti

I would like to know how to do it for each row.

1 Commento

Ameer Hamza
Ameer Hamza il 29 Apr 2018
Please delete this answer, and discuss it in the comment section.

Accedi per commentare.

Categorie

Community Treasure Hunt

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

Start Hunting!

Translated by