Calculation of conditional expectations

2 views (last 30 days)
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
Walter Roberson
Walter Roberson on 3 Jun 2018
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
Walter Roberson
Walter Roberson on 3 Jun 2018
Is nnz more efficient than sum?
In my timing tests, Yes.
Greg
Greg on 3 Jun 2018
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)

Tags

Products

Community Treasure Hunt

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

Start Hunting!