Check matrix element

100 Views Asked by At

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?

2

There are 2 best solutions below

2
On BEST ANSWER

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.

2
On

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