Create matrix with elements representing distance from centre of matrix
20 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Jason
am 29 Jan. 2021
Kommentiert: Image Analyst
am 31 Jan. 2021
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 Kommentare
Akzeptierte Antwort
Image Analyst
am 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 Kommentare
Image Analyst
am 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.
Siehe auch
Kategorien
Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!