Calculate percentage of zeros and ones in my vector?

15 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

Star Strider
Star Strider il 5 Giu 2014
Modificato: Star Strider il 5 Giu 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 Commenti
Image Analyst
Image Analyst il 24 Set 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 il 24 Set 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

Accedi per commentare.

Più risposte (1)

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

Categorie

Scopri di più su Get Started with MATLAB in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by