Calculate percentage of zeros and ones in my vector?

12 visualizaciones (últimos 30 días)
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.

Respuesta aceptada

Star Strider
Star Strider el 5 de Jun. de 2014
Editada: Star Strider el 5 de Jun. de 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 comentarios
Image Analyst
Image Analyst el 24 de Sept. de 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 el 24 de Sept. de 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

Iniciar sesión para comentar.

Más respuestas (1)

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

Categorías

Más información sobre Get Started with MATLAB en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by