Counting values above a threshold within a matrix.

Hello,
Im looking at finding a way of counting values that are >0 from a matrix, for example:-
if true %if statement used to display matrix correctly
00100
01110
11111
01110
00100
end
Would provide the output 1,3,5,3,1. Any help would light up my day.
Cheers
Gareth

1 件のコメント

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 9 月 17 日
編集済み: Azzi Abdelmalek 2012 年 9 月 17 日
is this your matrix?
0 0 2 0 0
0 3 4 5 0
1 2 3 4 5
0 6 5 4 0
0 0 3 0 0

サインインしてコメントする。

 採用された回答

Greg
Greg 2012 年 9 月 17 日

0 投票

sum(myMat>0, 2)
the result is the number of values in each row > 0.

3 件のコメント

Greg
Greg 2012 年 9 月 17 日
編集済み: Greg 2012 年 9 月 17 日
to get the number of values in each row > 0 use:
sum(myMat > 0, 2)
to get the number of values in each column > 0 use:
sum(myMat > 0, 1)
the default value is 1 so the following is another way to get number of values in each column > 0:
sum(myMat > 0)
Gareth Evans
Gareth Evans 2012 年 9 月 17 日
A little closer to the solution, for which i really appreciate.
Say the matrix is a 24X365 where 24 is equal to hours and 365 to days. This matrix contains values which relate to the intensity of sunlight hourly per day for 365 days.
How can i create an output from the matrix that will provide a matrix (1X365) with each cell in the matrix (1x365) containing values that exceed 0. or in other words how many hours a day sunlight per day?
I hope this makes the problem clearer as the code given above is outputting the wrong dimensions. and i cant seem to get the right solution by playing with it.
cheers guys.
Gareth Evans
Gareth Evans 2012 年 9 月 17 日
Wonderful. Thankyou..(-:

サインインしてコメントする。

その他の回答 (2 件)

Babak
Babak 2012 年 9 月 17 日

0 投票

you can run the below function for each of your numbers:
function num_of_1s = no1(n)
if n==0
num_of_1s = 0;
else
length = floor(log10(n))+1;
num_of_1s = 0;
for j=length:-1:1
if floor(log10(n)) == j-1
num_of_1s = num_of_1s +1;
n = n-10^(j-1);
end
end
end
end
Then say for example:
no1(1010111)
which returns
5

1 件のコメント

Gareth Evans
Gareth Evans 2012 年 9 月 17 日
I do apologise, I believe that the way i used to display the matrix using this forum editor might of caused a little confusion. I used the code tab to enable me to display the matrix as you would write down on a piece of paper.
00200 03450 12345 06540 00300 would be a 5x5 matrix.
Could you solve this problem with out an if loop?
with thanks.

サインインしてコメントする。

nah
nah 2012 年 9 月 17 日

0 投票

A simple way is:
myMat =
0 0 2 0 0
0 3 4 5 0
1 2 3 4 5
0 6 5 4 0
0 0 3 0 0
[nrows,ncols] = size(myMat);
counts_above_0 = zeros(nrows,1);
for rx = 1:nrows
counts_above_0(rx,1) = length(find(myMat(rx,:)>0));
end

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2012 年 9 月 17 日

コメント済み:

2023 年 9 月 5 日

Community Treasure Hunt

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

Start Hunting!

Translated by