Calculate percentage of zeros and ones in my vector?

15 vues (au cours des 30 derniers jours)
Bojan
Bojan le 5 Juin 2014
I've already have my vector and number of zeros and ones with this code:
u=[1 1 1 1 1 0 0 0 1 1 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0]
transitions=(find(u~=[u(2:end), u(end)+1]));
value=u(transitions)
transitions(2:end)=transitions(2:end)-transitions(1:end-1)
i get this
value =
1 0 1 0 1 0
transitions =
5 3 2 7 5 3
Now, please if someone could help me and explain how I can get percentage of ones and percentage of zeros in my vector (all together, and by each value). Thank You very much.

Réponse acceptée

Star Strider
Star Strider le 5 Juin 2014
Modifié(e) : Star Strider le 5 Juin 2014
This works:
u=[1 1 1 1 1 0 0 0 1 1 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0]
pctg_1 = sum(u)/size(u,2) * 100 % Percentage of ‘1’
pctg_0 = 100 - pctg_1 % Percentage of ‘0’
produces:
pctg_1 =
48.0000
pctg_0 =
52.0000
  11 commentaires
Image Analyst
Image Analyst le 24 Sep 2017
That's because he used size(u, 2) to count the number of column. This fix will make it work for any array, regardless of the shape/dimensions and regardless of what values are in there (0, 1, or other values):
percentageOfOnes = sum(u(:) == 1) / numel(u) * 100 % Percentage of ‘1’
Walter Roberson
Walter Roberson le 24 Sep 2017
The original Question asked specifically about vectors. For arrays,
pctg_1 = sum(u(:))/numels(u) * 100 % Percentage of ‘1’
Or,
pctg_1 = nnz(u)/numels(u) * 100 % Percentage of ‘1’
Or more simply,
pctg_1 = mean2(u) * 100 % Requires Image Processing Toolbox

Connectez-vous pour commenter.

Plus de réponses (1)

Vijayramanathan B.tech-EIE-118006077
function a = zero_stat(b)
c=(sum(b(:))/numel(b))*100;
a=100-c;

Catégories

En savoir plus sur Get Started with MATLAB dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by