user2304650
user2304650

Reputation: 3

Infinite While loop in Matlab

I'm trying to write a script file in Matlab that will plot the trajectory of a ball thrown at a specific angle (a), velocity (v) and from an initial height (y0). I have the equation and want Matlab to plot the path of the ball in flight. However, I want it to only plot it until it hits the ground (y = 0).

To do this I have used a while loop, but it seems to never satisfy the condition and just run forever. I'm sure the condition can be met after a number of iterations from x, but it just goes on for minutes, what's wrong?

The code is as follows.

    % Trajectory Plotter with cutoff
    clear all
    close all 
    clc

    y0 = input('Enter a value for y0 in meters: ');

    if y0 < 0 
        disp('Please enter a positive value for y0')
    end

    a = input('Enter a value for theta in degrees: ');
    g = 9.81;
    v = input('Enter a value for initial velocity in m/s: ');

    x = 0;
    y = y0 + x*tand(a) - (g*x.^2)/(2*(v*cosd(a))^2)

    while y >= 0
        x = x+0.2
    end

    plot(x,y);

Apologies if this is a trivial problem, I'm new to Matlab/programming.

Thanks.

Upvotes: 0

Views: 1842

Answers (2)

Roney Michael
Roney Michael

Reputation: 3994

It's true that you do indeed need to update the loop control variable y as well within the while loop, but that's not all that's amiss with your code.

Since you're looking to plot the trajectory, you'll need to preserve the values of x and y computed; here they're simply being overwritten.

The following will achieve what you seem to need:

% Trajectory Plotter with cutoff
clear all
close all 
clc

y0 = input('Enter a value for y0 in meters: ');

if y0 < 0 
    disp('Please enter a positive value for y0')
end

a = input('Enter a value for theta in degrees: ');
g = 9.81;
v = input('Enter a value for initial velocity in m/s: ');

x = 0;
y = y0 + x*tand(a) - (g*x.^2)/(2*(v*cosd(a))^2);

X = x;
Y = y0;

while y >= 0
    x = x+0.2;
    y = y0 + x*tand(a) - (g*x.^2)/(2*(v*cosd(a))^2);

    X = [X x];
    Y = [Y y];
end

plot(X,Y,'--o');

Here, before overwriting x and y, their values are being appended to X and Y respectively and are thus preserved in those variables.

Upvotes: 0

user2271770
user2271770

Reputation:

It is true, the while loop is the problem. If your condition (in this case y >= 0) is not influenced by the execution of your loop, then the truth value of the condition will never change. It's like putting paintbrush strokes on a wall and waiting for the opposite wall to get painted...

Now, for this particular problem, you might want to update the y's value too, after updating the x's value:

while y >= 0
    x = x+0.2;
    y = y0 + x*tand(a) - (g*x.^2)/(2*(v*cosd(a))^2);
end  

Upvotes: 1

Related Questions