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 个评论

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.
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.

请先登录,再进行评论。

 采纳的回答

sum(A)./nnz(A>=0)

3 个评论

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.

请先登录,再进行评论。

更多回答(0 个)

类别

在 帮助中心 和 File Exchange 中查找有关 Introduction to Installation and Licensing 的更多信息

产品

标签

Community Treasure Hunt

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

Start Hunting!

Translated by