MATLAB: Create matrix with elements representing distance from centre of matrix

arrayindexMATLAB

Hello. If i have a 3×3, 5×5 or 7×7 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 3×3 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

Best Answer

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