Calculate percentage of zeros and ones in my vector?

19 ビュー (過去 30 日間)
Bojan
Bojan 2014 年 6 月 5 日
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
Vijayramanathan B.tech-EIE-118006077 2018 年 1 月 21 日
function a = zero_stat(b)
c=(sum(b(:))/numel(b))*100;
a=100-c;

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by