Calculate percentage of zeros and ones in my vector?

16 次查看(过去 30 天)
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.

采纳的回答

Star Strider
Star Strider 2014-6-5
编辑:Star Strider 2014-6-5
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 个评论
Image Analyst
Image Analyst 2017-9-24
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 2017-9-24
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

请先登录,再进行评论。

更多回答(1 个)

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

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by