Search code examples
matlabcalculus

Using MATLAB to create Position, Velocity, and Acceleration plots


I am extremely new to MATLAB (as in just picked it up today) and trying to create basic Position, Velocity, and Acceleration plots.

I have this so far:

theta = (0:1:pi);
beta = asin((h+ b*cos(theta))/d);
x = b*cos(theta) + d*cos(beta);

plot(radtodeg(theta), x*1000);

b, d, and h are constants, and I'm trying to plot Position (x), Velocity (x_dot), and Acceleration (x_dd) versus the angle theta. This first part works fine and spits out a plot for x.

Is there a way to get the Velocity and Acceleration plots without me having to find the derivative of my function by hand and plotting that? I'm not sure what MATLAB's capabilities are. I don't need the actual derivatives, just the plot, so if I can avoid doing the derivations by hand I would like to. I looked into diff but it looked as though it required syms which I'd also like to try to avoid.

Any help is appreciated. Thanks.


Solution

  • You could use diff in another way, i.e., when you do diff(x) it will return a vector with length 1 less than the original one. Here is the modified version of your code:

    h = 5; b = 2; d = 4;
    theta = (0:0.1:pi);
    beta = asin((h+ b*cos(theta))/d);
    
    % Position 
    x = b*cos(theta) + d*cos(beta);
    plot(radtodeg(theta(1:end-2)), x(1:end-2));
    
    % Velocity 
    hold on;
    v = diff(x);
    plot(radtodeg(theta(1:end-2)), v(1:end-1));
    
    % Acceleration
    a = diff(v);
    plot(radtodeg(theta(1:end-2)), a);
    
    legend('Position', 'Velocity', 'Acceleration');
    hold off;
    

    Here, I assumed some random numbers for h, b, and d. Also, beta has imaginary numbers. You have to take care of that.