Calculating weighted mean of large matrix
9 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Jan
on 9 Mar 2021
Edited: Jan
on 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 Comment
Jan
on 10 Mar 2021
Of course you can modify the weights as you want, e.g. dist - max(dist(:)), 1 ./ dist, etc
More Answers (0)
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!