How can I calculate a weighted mean in Matlab?

I have a 180-by-360 matrix of (surface temperature) values and I want to calculate a weighted average of all values given in this matrix. However, I need to weight these values with respect to latitude. Is there a way to calculate a weighted mean in Matlab? Please help me.
Thanks in advance for any help!
- Jan-Erik

댓글 수: 1

shelley
shelley 2015년 10월 20일
Normally taking dim 1 mean of some, say 3x5 matrix A, can be seen as w=[1/3 1/3 1/3], and w*A returns you the answer.
Now if we want to take dim 1 weighted mean of A, we can set our weight in w = [1/6 2/3 1/6], then take w*A, which should return you a 1x5 row vector.

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

 채택된 답변

Matt J
Matt J 2013년 2월 18일
편집: Matt J 2013년 2월 18일

0 개 추천

If A is your 180x360 matrix and W is a 180x1 vector of weights for the latitudes, do
weighted_mean = mean(W.'*A,2);

댓글 수: 6

hi, i think the question is how to generate the weights ( normalized or not) , do you have an idea on how to do so using Gaussian kernel?
Jan-Erik
Jan-Erik 2013년 2월 18일
Thank you for your help!
Matt J - your answer seems not to work. Is there a typo? Here's the command lines: A = rand(180,360).*100; w = cos(linspace(-pi/2,pi/2,180)); weighted_mean = mean(w.'*A,2) ??? Error using ==> mtimes Inner matrix dimensions must agree.
Youssef - I'm not sure what you mean with Gaussian kernel.
I specified my assumption that w is 180x1 (i.e., a column vector). Never mind, though. You can just omit the transpose if you want to maintain it in row form.
weighted_mean = mean((w/sum(w))*A,2)
I've also normalized w here so that the weights sum to one.
Jan-Erik
Jan-Erik 2013년 2월 20일
Thanks!
weighted_mean = mean(bsxfun(@times,A,w'),2)
weighted_mean = mean(bsxfun(@times,A,w'),2)
If that's what the OP intended, it would be more efficient to do
weighted_mean=w'.*mean(A,2);

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

추가 답변 (2개)

John Hock
John Hock 2019년 4월 28일

0 개 추천

Hi Everyone
I just want to ask one thing that if i have 2d array 2*4 and want to get weighted average with vector of 1*4
i want first row of A get multiplied with B and give weighted average as an output similarly for next row.
Please help

댓글 수: 2

Try
B = repmat(B, [2, 1]) % Make B 2*4
weightedMeans = sum(A.*B, 1); % Get weighted means within a row going across columns.
Hello,
I have the following questuin: I have a matrix e.g
[5 3 3 1
3 4 5 2
5 0 0 0
3 4 5 2]
For this matrix I have to make a weighted average for each row. That is [5+3+(4/5)*(3+1)] /4=16/5. Also, if there is only one number and the zero (row 3) the weighted average should be [5+0+0+0] / 1 =5 and the end we choose the largest weight average. How does this work?

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

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

2013년 2월 18일

답변:

2019년 10월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by