Transformation of matrix indices in polar coordinates - quicker way

45 Ansichten (letzte 30 Tage)
Hey :)
To problem is a quite simple one I have a matrix say n x m and every element represents a z-value. What I want to do is transform the incices n and m into polar cooordinates based on the image center.
The center of the matrix is denoted as (n0, m0) and the last pixel by (nMax, mMax). So I used two for loops one cycling n one cycling m and then use cart2pol to transform the coordinates and save them to an array.
%array for output data
polarCoordinates = [];
%cycle through all pixels
for n:nMax
for m:mMax
%transform coordinates for singel pixel
[theta, rho, z] = cart2pol(n-n0, m-m0, image(n,m));
%append coordinates for pixel to array
polarCoordinates = [polarCoordinates; theta, rho, z];
end
end
This approach works but given the two for loops it is very slow. So I am looking for an elegant solution to speed up the process.
I know cart2pol can handle arrays of x, y, z values for transformation, e.g. n,m,image(n,m). To form those arrays I'd need to cycle tha matrix with the for loops as well or maybe not? Any ideas?
Thanks for the help!

Akzeptierte Antwort

Neuropragmatist
Neuropragmatist am 14 Aug. 2019
You can just pass all of the indices to cart2pol as vectors:
mat = rand(120,100);
cent = size(mat)./2;
[rr,cc] = meshgrid(1:size(mat,1),1:size(mat,2));
[TH,R,Z] = cart2pol(rr(:)-cent(1),cc(:)-cent(2),mat(:));
polarCoordinates = [TH R Z];
figure
subplot(1,2,1)
imagesc(reshape(TH,size(rr)))
title('Theta')
subplot(1,2,2)
imagesc(reshape(R,size(rr)))
title('Rho')
Here I used meshgrid to get the row and column indices of every matrix element but something similar could probably be achieved using sub2ind.
I have followed your convention of giving cart2pol row indices then column indices but remember that row and column are not x,y (rows actually run along the y axis) so these might need to be reversed. You should check that TH and R are correctly oriented for what you expect.
Hope this helps,
M.
  2 Kommentare
Markus Altthaler
Markus Altthaler am 14 Aug. 2019
Hey Metioche,
thank you for the quick response!
The method works very well. Regarding your concerns about indices not being aligend properly with x and y axes , this is a good remark but in my case irrelevant as I am mainly interested in a z value over rho polt afterwads ;)
Anshuman Pal
Anshuman Pal am 11 Nov. 2019
How exactly would one deal with the data getting transposed here? I tried changing the following, but it didn't work:
[rr,cc] = meshgrid(1:size(mat,1),1:size(mat,2));
to
[rr,cc] = meshgrid(1:size(mat,2),1:size(mat,1));

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and Arrays 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!

Translated by