Matrix Average of neighbour values

6 ビュー (過去 30 日間)
Kiwala Martin
Kiwala Martin 2020 年 2 月 19 日
編集済み: Kiwala Martin 2020 年 2 月 19 日
After creating a matrix of order MxM it will then output a new matrix in which each element is calculated from the original matrix by finding the average of each element adjacent (horizontally, vertically, excluding diagonal elements) to the original element including the element itself.
For example
M=3
then matrix is
[1,2,3;6,5,4;7,8,9]
element
�(1,1) = (1 + 2 + 6 )/ 3 = 3
(1,2) = (1 + 2 + 3 + 5 ) /4 = 3
  1 件のコメント
Kiwala Martin
Kiwala Martin 2020 年 2 月 19 日
I have tried using :
Result = conv2(M, ones(3), 'same')./conv2(ones(3),ones(3), 'same')
But this approach includes the diagonal neighbours, how can i exclude them.
Thanks in advance

サインインしてコメントする。

採用された回答

Marta G
Marta G 2020 年 2 月 19 日
Hello!
I think using conv2 was a great idea. However, you should use it like this
DIM=3;
aa=[0 1 0;1 1 1;0 1 0];
matrix=[1,2,3;6,5,4;7,8,9];
conv2(matrix, aa, 'same')./conv2(ones(DIM),aa, 'same')
This way of convolution does not account for diagonal neighbours. Afterwards, if you do not want decimals, use ceil or round depending on your desire.
Hope this helps :)
  3 件のコメント
Marta G
Marta G 2020 年 2 月 19 日
編集済み: Marta G 2020 年 2 月 19 日
You are welcome! The good thing is that you dont need to change de aa matrix.
M=4
N=3
matrix=[1,2,3;6,5,4;7,8,9;7,8,9]
aa=[0 1 0;1 1 1;0 1 0];
conv2(matrix, aa, 'same')./conv2(ones(M,N),aa, 'same')
Since you are using 'same' : returns the central part of the convolution that is the same size as matrix.
You still have the same dimensions as before while using aa still. With matrix being:
1 2 3
6 5 4
7 8 9
7 8 9
you get
ans =
3.0000 2.7500 3.0000
4.7500 5.0000 5.2500
7.0000 7.4000 7.5000
7.3333 8.0000 8.6667
Kiwala Martin
Kiwala Martin 2020 年 2 月 19 日
編集済み: Kiwala Martin 2020 年 2 月 19 日
Thank you very much Marta.
This has been very helpful.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by