Calculating weighted mean of large matrix
32 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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.
0 commentaires
Réponse acceptée
Jan
le 9 Mar 2021
Modifié(e) : Jan
le 9 Mar 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 commentaire
Jan
le 10 Mar 2021
Of course you can modify the weights as you want, e.g. dist - max(dist(:)), 1 ./ dist, etc
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!