Calculation of conditional expectations

Suppose I have a vector A and I would like to calculate the sum of the elements in A divided by the number of positive elements of A. Please advise.

6 Comments

Sounds like the mean of A after you set all negative values of A to 0. What have you tried, and where are you stuck?
No, if you set the negative values to 0 then the count of those 0 get included in the mean. Furthermore, the negative values are to be included in the sum even if the count is only to be for the positive values.
sum(A(:,1))./sum(A(:,1)~=0);
That code assumes you have a row vector.
That code counts the number of non-zeros in the vector, instead of counting the number of positive values.
Greg
Greg on 3 Jun 2018
Edited: Greg on 3 Jun 2018
Touche, I wasn't thinking very hard. Was trying to spark some thinking in the poster, rather than hand out an answer.
And unless I'm really out of it, A(:,1) is a column vector.

Sign in to comment.

 Accepted Answer

Stephen23
Stephen23 on 3 Jun 2018
Edited: Stephen23 on 3 Jun 2018
sum(A)./nnz(A>=0)

3 Comments

Is nnz more efficient than sum? Since A >= 0 returns logicals, sum should be same as nnz, correct?
Is nnz more efficient than sum?
In my timing tests, Yes.
Fascinating. I'll have to start implementing where I can. Normally, I just skip those ones since the difference in typical cases is going to be negligible.

Sign in to comment.

More Answers (0)

Categories

Products

Tags

Asked:

on 3 Jun 2018

Commented:

on 3 Jun 2018

Community Treasure Hunt

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

Start Hunting!