Search code examples
matlabmatlab-figure

Plotting Ellipse in Matlab


In addition to my R programming course, I am also taking an intro to LaTeX course. We have a new assignment which is to generate a graph of a given function (in Matlab), save it and then recall it in LaTeX code as though we're making a publication. My Matlab is a little rusty, and I don't think that I quite got the code right. Furthermore it doesn't look anything like the example we were given for reference. The function that we were asked to plot is the following: 1 = x^(2)/9 - y^(2)/4

What my image is supposed to look like: What my image is supposed to look like:

What my Matlab code generated: What my Matlab code generated:

function graph_1

clc; clear all; 

a = 9;
b = 4;
x0 = 0;
y0 = 0;
t = -pi:0.1:pi;
x = 1 - x0 + a*cos(t);
y = 1 - y0 + a*sin(t);

figure(1); clf; 
    
plot(x,y,'b','linewidth',1)
set(gca, 'fontsize', 12)
xlabel('X')
ylabel('Y')
grid on

end

Once I get the code to run in Matlab, I get a weird looking ellipse and it doesn't look "pretty" like the one my professors gave us as reference which I have attached. The full assignment is asking us to generate a plot with our programming language of choice, save it, and then have the LaTeX code actually recall the file and then insert into a pdf. How would I export this figure to somehwere else in my computer?


Solution

  • Originally, I thought I needed to plot an ellipse, but found that I actually needed to plot a hyperbola. At any rate, I figured out how to plot both functions, because their format is nearly identical, and have included the code for the ellipse. In my experience, the best way to plot these functions was to use the fimplicit function in Matlab. To fully understand how it works, I strongly suggest typing help fimplicit into the command window. From there, you can see the documentation and examples of how to plot functions like these.

    This is the code I ran in Matlab to make things work correctly.

    function graph_1
    
    clc; clear; 
    
    f1 = @(x,y) x.^(2)/9 + y.^(2)/4 - 1;
    
    fimplicit(f1, 'b');
    grid on;
    axis equal;
    
    print(figure(1), '-dpng') %% Saves a picture of the image in png format. 
    
    end
    

    And then this is the ellipse I generated:

    Plot of an Ellipse.