Why doesn't my code return the correct value when I try to find the average of the values greater than 0?

조회 수: 1 (최근 30일)
Hi,
I'm trying to find the average of the values that are greater than 0 and the average of values less than 0. I wrote the following code:
sample = xlsread('sample.xlsx', 1); %Download spreadsheet to MATLAB
avgGreaterThan0 = mean(sample(:)>0); %finds the average of values > 0
avgLessThan0= mean(sample(:)<0); %finds the average of values < 0
The outputs are, 0.232876712328767 (avg. when values > 0) and 0.767123287671233 (avg. when values < 0). However I preformed the task manually to find it should be 0.132517148 (avg. when values > 0) and -0.043091451 (avg. when values < 0.)
Could you please help me with my code?
Best, A

채택된 답변

Jan
Jan 2017년 3월 8일
sample(:)>0 replies a logical array. Then mean(sample(:)>0) calculates the average number of the elements greater than 0, not the average of the values itself. For this use:
avgGreaterThan0 = mean(sample(sample(:) > 0));
avgLessThan0 = mean(sample(sample(:) < 0));
  댓글 수: 3
Image Analyst
Image Analyst 2017년 3월 8일
Then you didn't use Jan's code. Here's proof Jan's code works:
sample = randi(100, 1, 1000) - 50
avgGreaterThan0 = mean(sample(sample(:) > 0))
avgLessThan0 = mean(sample(sample(:) < 0))
See results:
avgGreaterThan0 =
25.729
avgLessThan0 =
-24.485
Alexandra Brian
Alexandra Brian 2017년 3월 8일
You're right Image Analyst. Thanks guys! I had an error with my parenthesis.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Web Services에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by