Search code examples
matlabmatlab-figure

Plot vector field within given region (between two circles) in matlab


I want to plot below vector field in Matlab:

 u = cos(x-x_0).*y-y_0;
 v = sin(x+x_0).*y+y_0;

I can do it easily in a grid, for example from -2 to 2 in x and y direction:

x_0=2; y_0=1;
[x,y] = meshgrid(-2:0.2:2, -2:0.2:2);
figure
quiver(x,y,u,v)

But I want to plot the vector field in a certain region which isn't square like above. The region I want to plot the vector field is the region between two circles, both centered at (x_0,y_0) with radii equal to r_1=5 and r_2=10

How can I do that?


Solution

  • Set up your radii, centre of circle and x,y variables like so

    r1 = 5; r2 = 10;  % Radii of your circles
    x_0 = 0; y_0 = 1; % Centre of circles
    [x,y] = meshgrid(x_0-r2:0.2:x_0+r2,y_0-r2:0.2:y_0+r2); % meshgrid of points
    

    Then get which points are within the annulus described by the two circles, do this by using the circle equations which define the region:

    idx = ((x-x_0).^2 + (y-y_0).^2 > r1^2 & (x-x_0).^2 + (y-y_0).^2 < r2^2);
    

    Define your vector field

    u = cos(x-x_0).*y-y_0;
    v = sin(x+x_0).*y+y_0;
    

    Then plot the vector field of these points using quiver like you did:

    quiver(x(idx),y(idx),u(idx),v(idx));
    

    Output:

    enter image description here


    Edit:

    If your vector field is complicated, you would save a lot of computation time by first removing elements from x and y which you are not interested in. After calculating idx, do:

    x = x(idx);
    y = y(idx);
    

    Then calculate u and v and you can plot by simply calling quiver(x,y,u,v).