Calculating weighted mean of large matrix

조회 수: 8 (최근 30일)
Álvaro Macías López
Álvaro Macías López 2021년 3월 9일
댓글: Jan 2021년 3월 10일
Hi everyone,
I am new to matlab and I'm facing a problem right now. I need to calculate the weighted mean of all elements of a matrix, where each element's weight is determined by its distance to the centre, and the centre weights more. For example in a 3x3 matrix, the centre would be 1/4, adjacent elements 1/8 and so on. I know about mean function, so the only problem is creating the weight matrix, which may be 400x600 for instance. Is there a way to create such matrix in matlab other than manually? I've been told to avoid loobs in matlab, and I know there's a very complete set of functions to do the most common tasks, I just couldn't find one fot this.
Thank you all.

채택된 답변

Jan
Jan 2021년 3월 9일
편집: Jan 2021년 3월 9일
Loops are very slow in Matlab...
...version 5.3 from 1999. Since Matlab 6 the JIT acceleration improves the speed of loops massively, but the rumors about slow loops are still fancy.
But of course, vectoorized code is usually faster than loops, nicer and easier to maintain.
To get a weighting matrix with a higher factor near to a specific position:
data = rand(400, 600);
c = [150.2, 370.7]; % The "center"
dist = ((1:400).' - c(1)).^2 + ((1:600) - c(2)).^2; % Squared distance
% do you need the absolute distance?
dist = sqrt(dist);
weight = dist; % Or any function of the distance
weightedMean = mean(data .* weight, 'all') / sum(weight, 'all');
  댓글 수: 1
Jan
Jan 2021년 3월 10일
Of course you can modify the weights as you want, e.g. dist - max(dist(:)), 1 ./ dist, etc

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by