MATLAB Answers

Calculate mean of certain values in a vector

27 views (last 30 days)
Hi!
I have two problems I'd need some help with.
I have a column vector (25 x 1) with positive and negative values. It has the following values:
1716000
0
-2400000
-5124000
880000
-51000
-192000
656000
165000
702000
1456000
1700000
-550000
46000
8272000
-660000
-162000
2000
22000
210000
2817000
285000
-1400000
840000
570000
First problem: Out of these values, I would first like to calculate the average (mean) of all the values that are not negative.
I tried the following script, but it gives a weird answer of 0,68:
OnlyPositives = profit>=0;
avgProfitNoLoss = mean(OnlyPositives)
I don't know why it gives me the answer of 0,68 so the first question is how I can correct this.
The next step then is to calculate the average of the values that are zero and the values that are negative. But, the first problem above needs to be addressed first.
Thank you in advance for any help/suggestions!

  0 Comments

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 25 Sep 2019
You created a logical vector with ‘OnlyPositives’. Use it to calculate the mean as:
avgProfitNoLoss = mean(profit(OnlyPositives))
producing:
avgProfitNoLoss =
1196411.76470588
that is likely the result you want.
The average of the values that are zero will be zero, so you can avoid that calculation.

  3 Comments

Daniel Miller
Daniel Miller on 25 Sep 2019
Wonderful, this solved the problem. Thank you very much, Star Strider!
Carlos Maqueda
Carlos Maqueda on 27 Mar 2020
I had the same problem, working with digital signs (+,-). Thanks too

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!