Calculate percentage of zeros and ones in my vector?

好久不见. 提交于 2019-12-31 03:49:09

问题


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.


回答1:


If I understand you correctly it is very simple:

p1=sum(u)./numel(u); % is the percentage of ones
p2=1-p1;             % is the percentage of zeros   

Matlab has even this spesific function called tabulate that creates a frequency table just for that:

tabulate(u)

Value    Count   Percent
      0       13     52.00%
      1       12     48.00%



回答2:


This is just psuedocode so it'll need to be translated, but here's a potential solution:

total = 0;
total_ones = 0;
total_zeroes = 0;

for(i=0; i<transitions.length; i++){
    total += transitions[i];
    if(value[i] == 0)
        total_zeroes += transitions[i];
    else
        total_ones += transitions[i];
}

print("Percent Zeroes: " + (total_zeroes/total)*100);
print("Percent Ones: " + (total_ones/total)*100);

#To print each group's percent it'd be along the lines of the following:
for(i=0; i<transitions.length; i++){
    print("Percent of total comprised of this group: " + (transitions[i]/total)*100)
}


来源:https://stackoverflow.com/questions/24065388/calculate-percentage-of-zeros-and-ones-in-my-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!