Create matrix with elements representing distance from centre of matrix
17 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Image Analyst
on 31 Jan 2021
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 Comments
Image Analyst
on 31 Jan 2021
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.
See Also
Categories
Find more on Matrix Indexing 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!