Calculating weighted mean of large matrix
34 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
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
2021 年 3 月 10 日
Of course you can modify the weights as you want, e.g. dist - max(dist(:)), 1 ./ dist, etc
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!