1

I need a (rho,theta) meshgrid and to do that first I defined the meshgrid in Cartesian coordinates and then convert it to polar coordinates:

[X,Y] = meshgrid(x,y);
R = sqrt(X.^2+Y.^2);
PHI = atan2(Y,X);

Now what I get is a mesh in polar coordinates, but since it is a squared mesh, I get this thing

enter image description here

I say that the values greater than R are wrong and therefore I set them to zero. I did it in this way

for i = 1:1:length(R)
    for j = 1:1:length(R)
        if R(i,j) > a
            R(i,j) = 0;
        else
            R(i,j);
        end
    end
end

How can I do this less convoluted?

Adriaan
  • 17,741
  • 7
  • 42
  • 75
Shika93
  • 635
  • 4
  • 24

2 Answers2

3

For direct Cartesian to polar conversion of coordinates: use cart2pol.

[theta,rho] = cart2pol(x,y)

Then a simple logical check will do:

tmp = rho>R;
rho(tmp)=0; %=[] to delete completely
theta(tmp)=0;

For what it's worth: you can of course create a direct polar grid:

[theta,rho] = meshgrid(0:dtheta:theta,0:dR:R)

Finally: i and j denote the imaginary unit in MATLAB, and I'd argue against using them as regular variables for reasons mentioned in this post, but that's my opinion.

Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • I thought to create a polar grid directly but I was having issues to plot the results using `quiver` due to the different dimension of the matrix `theta` and `rho`. With the solution that I choose (cartesian-polar-cartesian again) I have a squared mesh, easier to manage – Shika93 Nov 19 '18 at 22:26
  • @Shika93 you could just make your `theta` and `rho` vectors which you feed to `meshgrid` the same length, and then `quiver` is fine with it. Anyway the `cart2pol` does basically the same as what you did by hand, just wrapped in a handy function. – Adriaan Nov 20 '18 at 09:34
1

If we say that a is the limit you want to use you can use below code instead of the for loop:

R = (R<=a).*R

Or you can use as well:

R(R>a) = 0
Cedric Zoppolo
  • 4,271
  • 6
  • 29
  • 59
  • Just notice that in your code you used `R` to denote radius and `a` to denote the limit. Whereas in the figure you use `R` as the limit and `rho` for radius. I used the notation you stated in your code. – Cedric Zoppolo Nov 19 '18 at 22:07
  • I like the second option. Oh yes I didn't follow the notation that I used in my code inside the image, sorry. It was just to clarify what I needed. Thanks – Shika93 Nov 19 '18 at 22:21