Unable to store data in while loop to plot

1 view (last 30 days)
MadT
MadT on 23 Feb 2018
Answered: Naman Kaushik on 22 Jun 2023

I am trying to display a smooth graph/plot of the position over time, but I cannot for the life of me figure out how to store the values in order to display the data from he loop. here is the code:

%%Initialized Conditions
clear all;close all;clc;
g = 32.2 ./6; %gravity constant in ft/s^2
h = randi([1000 10000],1); %initial height
v = randi([-100 -40],1); %initial velocity
weight = 2500; %lbs
mass = weight./g; %craft mass (tons/gravity)
playing_flag = 1;
t = 0; %time elapsed in seconds
dt = 1; %time interval in seconds
vmax = 7; %max successful landing speed in ft/s
%%Introduction
fprintf('You are in a %.0f lb spacecraft\n',weight);
fprintf('Try to land with a speed of less than %.0f ft/s\n',vmax);
%%Game loop until done
while playing_flag==1
    %%current position and velocity
   fprintf('\nTime:%3.0f sec, Altitude: %6.1f ft, Velocity: %5.1f ft/s\n',t,h,v);
    %%user input
    input_flag = 1;
    while input_flag==1
        fprintf('<strong>Please enter a vertical thrust value.</strong>\n');
        thrust = input('*Thrust input must be between -10 and 10(k-lbs/s)* ');
        if isempty(thrust)
            thrust = 0;
        end
        if abs(thrust)<=10
            input_flag=0;
        else
            fprint('Invalid input. Thrust must be between -10 and 10\n');
        end
    end
    %%calculate new values
    a = -g + thrust*1000./mass;
      %time to hit the ground from current position
      %if it is less than dt, use it
      thit=roots([a./2 v h]);
      if length(thit)>=1 && isreal(thit(1)) && thit(1)>0 && thit(1)<dt
          dt=thit(1);
      end
      if length(thit)>=2 && isreal(thit(2)) && thit(2)>0 && thit(2)<dt
          dt=thit(2);
      end
      h = h + v.*dt + a./2.*dt.*dt;
      v = v + a.*dt;
      t = t + dt;
      %%check if landed
      if abs(h)<=0.1
          playing_flag = 0;
          if abs(v)<vmax
              msg = 'Successful landing!';
          else
              msg = 'Houston, we have a problem. Spacecraft down.';
          end
          fprintf('%s \nYou landed with a velocity of %.1f ft/s\n',msg,v);
      end
  end
pause

Answers (1)

Naman Kaushik
Naman Kaushik on 22 Jun 2023
Hi MadT,
As per my understanding, you want to plot the result in the order that they appear.
To get the current time, you can use the “datetime” function in MATLAB and by setting the parameter “relativeDay” as “now”.
To plot the data, you can use a combination of the “plot” function of MATLAB with the “hold” functionality turned on.
For more information on the above-mentioned functions, you can refer to the following documentation:
For “datetime” function:
For “plot” function:

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!