Create matrix with elements representing distance from centre of matrix
13 次查看(过去 30 天)
显示 更早的评论
Hello. If i have a 3x3, 5x5 or 7x7 matrix or generally a nxn matrix where n is odd, i want each element to represent the distance from the centre of the matrix. I.e the top left element in a 3x3 matrix to represent up one row and left 1 column. I.e (1,-1).
I then want to unravel this matrix into a 1D vector but in a serpentine fashion rather than raster scan
0 个评论
采纳的回答
Image Analyst
2021-1-31
Jason if you want a for loop way of doing it, you can do this:
rows = 3;
columns = 4;
distances = zeros(rows, columns);
midRow = mean([1, rows])
midCol = mean([1, columns])
for col = 1 : columns
for row = 1 : rows
distances(row, col) = sqrt((row - midRow) .^ 2 + (col - midCol) .^ 2);
end
end
distances
Some results:
For 3,4:
distances =
1.8028 1.118 1.118 1.8028
1.5 0.5 0.5 1.5
1.8028 1.118 1.118 1.8028
For 3,3
distances =
1.4142 1 1.4142
1 0 1
1.4142 1 1.4142
For 4,4
distances =
2.1213 1.5811 1.5811 2.1213
1.5811 0.70711 0.70711 1.5811
1.5811 0.70711 0.70711 1.5811
2.1213 1.5811 1.5811 2.1213
2 个评论
Image Analyst
2021-1-31
Jason, it's so trivial, I'm sure you did it by now, but for what it's worth:
rows = 3;
columns = 4;
deltax = zeros(rows, columns);
deltay = zeros(rows, columns);
midRow = mean([1, rows])
midCol = mean([1, columns])
for col = 1 : columns
for row = 1 : rows
deltax(row, col) = col - midCol;
deltay(row, col) = row - midRow;
end
end
deltax
deltay
For the number of rows and columns shown, this is what you see.
midRow =
2
midCol =
2.5
deltax =
-1.5 -0.5 0.5 1.5
-1.5 -0.5 0.5 1.5
-1.5 -0.5 0.5 1.5
deltay =
-1 -1 -1 -1
0 0 0 0
1 1 1 1
But you might want to use meshgrid(). Just make sure you have the center location properly located with the right value. Like, if you have an even number of rows, the "middle" will not be exactly at a particular row, but in between existing rows.
更多回答(2 个)
darova
2021-1-31
What about this?
m = 5;
n = (m-1)/2;
[X,Y] = meshgrid(-n:n);
A = sqrt(X.^2+Y.^2)
surf(A)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!