How to use a loop for an array

조회 수: 1 (최근 30일)
KK
KK 2016년 3월 23일
댓글: Image Analyst 2016년 3월 26일
My question is:
I have an array with values ranging from 0 to 200 something, and I need to find the average value for a set range of the data i.e. I need to find the average value for 0 to 1, the average value of the data for 1-2, and so on until it hits the end. I would like to save that information in a new matrix that I can look up later on.
Any help is appreciated.
  댓글 수: 2
James Tursa
James Tursa 2016년 3월 23일
What about the boundary points? E.g., if a value is exactly 1, do you want it to be part of the 0-1 average and also the 1-2 average? Or do you want these averages to be mutually exclusive?
KK
KK 2016년 3월 23일
I suppose the range should be greater than the lower bound, less than or equal to the upper bound. I'll have to try out your method.

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

채택된 답변

Image Analyst
Image Analyst 2016년 3월 24일
If you have the Statistics and Machine Learning Toolbox, you can use grpstats(). It's a single line of code:
% Create sample data
r = 200 * rand(100000, 1);
% Now find means in every integer range.
means = grpstats(r, floor(r))
  댓글 수: 4
KK
KK 2016년 3월 26일
Is there a way to save the values used for each mean in an array so that I may apply further operations to that information?
Image Analyst
Image Analyst 2016년 3월 26일
In my code above, means is already an array. Do you mean like an array of those arrays? Like you want a 2D array or an array of structures?

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

추가 답변 (1개)

James Tursa
James Tursa 2016년 3월 23일
편집: James Tursa 2016년 3월 23일
Does something like this do what you want?
n = ceil(max(values));
x = bsxfun(@ge,values(:),0:n-1) & bsxfun(@le,values(:),1:n);
averages = sum(bsxfun(@times,values(:),x)) ./ sum(x);
averages(isnan(averages)) = 0;
  댓글 수: 1
KK
KK 2016년 3월 24일
The ceil function is pretty cool. I like the idea of using the bsxfun, but how would I be able to calculate the average for the data with a value between 0 and 1, or 1 to 2 (and so on), using this function, for all the values in the array?

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by