Calculating weighted mean of large matrix

9 Ansichten (letzte 30 Tage)
Álvaro Macías López
Álvaro Macías López am 9 Mär. 2021
Kommentiert: Jan am 10 Mär. 2021
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.

Akzeptierte Antwort

Jan
Jan am 9 Mär. 2021
Bearbeitet: Jan am 9 Mär. 2021
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 Kommentar
Jan
Jan am 10 Mär. 2021
Of course you can modify the weights as you want, e.g. dist - max(dist(:)), 1 ./ dist, etc

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by