Rain
Rain

Reputation: 375

Plotting circles with complex numbers in MATLAB

I want to make a figure in MATLAB as described in the following imageenter image description here

What I did is the following:

x = [1 2 3];
y = [2 2 4];
radius = [1 1.2 2.2];
theta = [-pi 0 pi];
figure;
scatter(x,y,radius)

How do I add an angle theta to the plot to represent a complex number z = radius.*exp(1j*theta) at every spacial coordinates?

Upvotes: 1

Views: 2354

Answers (2)

Chris M.
Chris M.

Reputation: 26

I went back over scatter again, and it looks like you can't get that directly from the function. Hopefully there's a clean built-in way to do this, and someone else will chime in with it, but as a backup plan, you can just add the lines yourself.

You'd want a number of lines that's the same as the length of your coordinate set, from the center point to the edge at the target angle, and fortunately 'line' does multiple lines if you feed it a matrix.

You could just tack this on to the end of your code to get the angled line:

x_lines = [x; x + radius.*cos(theta)];
y_lines = [y; y + radius.*sin(theta)];
line(x_lines, y_lines, 'Color', 'b')

I had to assign the color specifically, since otherwise 'line' makes each new line cycle through the default colors, but that also means you could easily change the line color to stand out more. There's also no center dot, but that'd just be a second scatter plot with tiny radius. Should plot most of what you're looking for, at least.

(My version of Matlab is old enough that scatter behaves differently, so I can only check the line part, but they have the right length and location.)

Edit: Other answer makes a good point on whether scatter is appropriate here. Probably better to draw the circle too.

Upvotes: 0

Max
Max

Reputation: 4045

Technically speaking, those are only circles if x and y axes are scaled equally. That is because scatter always plots circles, independently of the scales (and they remain circles if you zoom in nonuniformly. + you have the problem with the line, which should indicate the angle...

You can solve both issues by drawing the circles:

function plotCirc(x,y,r,theta)
% calculate "points" where you want to draw approximate a circle
ang = 0:0.01:2*pi+.01; 
xp = r*cos(ang);
yp = r*sin(ang);
% calculate start and end point to indicate the angle (starting at math=0, i.e. right, horizontal)
xt = x + [0 r*sin(theta)];
yt = y + [0 r*cos(theta)];
% plot with color: b-blue
plot(x+xp,y+yp,'b', xt,yt,'b'); 
end

having this little function, you can call it to draw as many circles as you want

x = [1 2 3];
y = [2 2 4];
radius = [1 1.2 2.2];
theta = [-pi 0 pi];

figure
hold on
for i = 1:length(x)
    plotCirc(x(i),y(i),radius(i),theta(i))
end

enter image description here

Upvotes: 2

Related Questions