필터 지우기
필터 지우기

Compute different length mean when cell equals number

조회 수: 1 (최근 30일)
Tyler Smith
Tyler Smith 2016년 10월 13일
댓글: Tyler Smith 2016년 10월 13일
I need to compute the mean of "x" number of rows in a column of data when a cell in another column is repeated. For example: I have the 2 columns of data:
A = (23, 23, 24, 25, 25, 25, 26, 26, 27, 27, 27, 27) and
B = ( 42, 43, 44, 38, 35, 36, 32, 28, 45, 46, 38, 29).
If a number repeats in "A" I need to get the mean of the value in the same row from "B". If it does not repeat, then the mean can just be the single number. An example output would be the mean in each cell like so:
Output = 42.5, 42.5, 44, 36.3, 36.3, 36.3, 30, 39.5, 39.5, 39.5, 39.5).
I have tried doing this with a while loop, but I'm relatively new to Matlab and haven't had much luck.
  댓글 수: 1
Geoff Hayes
Geoff Hayes 2016년 10월 13일
Tyler - is it safe to assume that the elements of A are ordered like the above such that all identical numbers are grouped together?

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

채택된 답변

Mostafa
Mostafa 2016년 10월 13일
Arr1 = [23, 23, 24, 25, 25, 25, 26, 26, 27, 27, 27, 27];
Arr2 = [42, 43, 44, 38, 35, 36, 32, 28, 45, 46, 38, 29];
uniArr1 = unique(Arr1);
for idx = 1:length(uniArr1)
Arr2(Arr1 == uniArr1(idx)) = mean(Arr2(Arr1 == uniArr1(idx)));
end
First, you extract the unique elements from the first array (basically the same elements without repeating any of them). Then you compare them to the original array, which gives you the indicies where they exist. You then take the elements from the second array as per these indicies, and equate them to their mean.
Expanded version:
uniArr1 = unique(Arr1);
for idx = 1:length(uniArr1)
indicies = (Arr1 == uniArr1(idx));
meanvalue = mean(Arr2(indicies));
Arr2(indicies) = meanvalue ;
end

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by