Plotting the same variable that changes 3 times on the one graph, for seven graphs at the same time.

8 views (last 30 days)
So I have this code that makes 7 plots, with different plots depending on which rocket is chosen (different rockets have different masses and thrusts, and experience different drag forces). I have to combine each graph so that the graph for each of the three rocket options is displayed on one graph, and there will be 7 graphs total in the end. In my own attempts, using hold on and hold off, I can get one out of 7 graphs to work as shown below. Also it would be good if I could have each line have a label beside saying whether it was bfhorse, derpy or nozomi but that might be a bit much. Anyway here's the code: clear variables % clear any old variables in the workspace close all % closes any plots open from previous runs %List all the variables needed
massEmptyRocket = 1500; % kg startingMassFuel = 7000; % kg massHorse = 75; %kg massTotal = massEmptyRocket + startingMassFuel +massHorse; % kg engineThrust = 130000; %N gravity = 9.81; %m/s/s dragCoefficient = .05; %constant involved in drag equation diameter=2; %diameter of rocket, used to get area crossSectionarea=(((diameter)/2)^2)*(pi); %area of rocket, used in drag calculation weight = massTotal * gravity; %downward force due to gravity dt = .1; % timeStep duration in seconds endTime = 325; % Time simulation ends at in seconds drag = zeros(1,endTime/dt); %Create empty vector of zeros for drag Data so it can be plotted at the end, unit is N density = zeros(1,endTime/dt); %Create empty vector of zeros for density Data so it can be plotted at the end, units are kg/m3 acceleration = zeros(1,endTime/dt); %Create empty vector of zeros for Acceleration Data the length of the simulation time = zeros(1,endTime/dt); %Create empty vector of zeros for time Data massFuel = zeros(1,endTime/dt); %Create empty vector of zeros for mass of fuel in kg, so it can be plotted at the end burnTime = 60; %Time Engines are firing for.
%code for reading in horse and rocket options fileID=fopen('horseyRocketOptions.txt','r'); %opens file for reading by readtable rocketTable= readtable('horseyRocketOptions.txt'); %puts info from file into a table
fileID2=fopen('horseyOptions.txt'); %same as above horseTable= readtable('horseyOptions.txt');
n=input('pick your horse, either bfhorse,derpy or nozomi (must be written as shown):\n','s'); %gets input of horse name and stores as a string called n,
if strcmp('bfhorse',n) %strcmp compares two strings and is either true or false for if they are the same or not. So if user inputs bfhorse for the horse name (n), strcmp will be true and the variables will be changed to the corresponding values in row 1 of the table. massEmptyRocket = rocketTable{1,3}; %have to use curly brackets or it makes the variable a table variable rather than a number. startingMassFuel = rocketTable{1,4}; engineThrust = rocketTable{1,5}; burnTime = rocketTable{1,6}; diameter = rocketTable{1,7}; massHorse = horseTable{1,2}; end
if strcmp('derpy',n) %strcmp compares two strings and is either true or false for if they are the same or not. So if user inputs deerpy for the horse name (n), strcmp will be true and the variables will be changed to the corresponding values in row 2 of the table. massEmptyRocket = rocketTable{2,3}; startingMassFuel = rocketTable{2,4}; engineThrust = rocketTable{2,5}; burnTime = rocketTable{2,6}; diameter = rocketTable{2,7}; massHorse = horseTable{2,2}; end
if strcmp('nozomi',n) %strcmp compares two strings and is either true or false for if they are the same or not. So if user inputs nozomi for the horse name (n), strcmp will be true and the variables will be changed to the corresponding values in row 2 of the table. massEmptyRocket = rocketTable{3,3}; startingMassFuel = rocketTable{3,4}; engineThrust = rocketTable{3,5}; burnTime = rocketTable{3,6}; diameter = rocketTable{3,7}; massHorse = horseTable{3,2}; end
%PART 5 - Add code here to use matlab function xlsread to read in density data %from excel. filename='DensityData.xlsx'; HD=xlsread(filename); %reading the data from excel file into variable HD adjustden=HD(:,2)*1000; %This takes the density values in the second column and converts them from g/cm^3 to kg/m^3
%start a loop to calculate our equations of motion at each Time Step
for t = 1:1:(endTime/dt) % t is the current TimeStep
time(t) = t*dt; % update the time vector with the new time step
%Calculate the velocity and Position, by integrating. velocity = cumtrapz(time,acceleration); position = cumtrapz(time,velocity);
%Add code for Parts 5-7 here. % PART 5. Write a function (findDensity.m) which calculates density as a function % of height above sea-level. Read in data once before the loop, see comment % above. First column is Altitude in km and the second in density in g/cm^3. density(t)=findDensity(position,adjustden,t); %Finds density at current timestep
%PART 6. Write a function (findDrag.m) which calculates the drag at each time step as a function % using the current velocity and current density (calculated in part 5) drag(t)= findDrag(density(t),velocity,t,crossSectionarea,dragCoefficient); %finds drag at current timestep %BONUS: Add paracute drag force calculation if the right altitidue requirements are %met.
%PART 7: Write a function (findWeight.m) which calculates the weight of the rocket at each time step. % Assume to fuel mass decrease linearly from the launch time to the end of the burn. [weight,massTotal,massFuel(t)]=findWeight(startingMassFuel,burnTime,massEmptyRocket,massHorse,gravity,t,dt); %Finds total mass of rocket, mass of fuel, and force of gravity in N acting on the rocket at the current timestep
%Equation of motion
if t <= (burnTime/dt) %while the engines are firing
%PART 8: Change code to use time varying for drag, weight and massTotal calculated in part 5-7. Replace equation with %acceleration(t) = (engineThrust - drag(t) - weight(t)) /massTotal(t); %need to make so drag is positive when moving downwards
acceleration(t) = (engineThrust - drag(t) - weight) /massTotal;%acceleration at current timestep while engines firing= engine thrust - drag at current time - weight at current time, all divided by the total mass at the current time.
% PART 8: Change code to use time varying for drag, weight and Mass Total calculated in Parts 5-7. Replace equation with %acceleration(t) = (- drag(t) - weight(t)) /massTotal(t);
else %when the engines have stopped firing
acceleration(t) = (-drag(t) - weight) /massTotal; %acceleration at current timestep while engines not firing= - drag at current time - weight at current time, all divided by the total mass at the current time.
end
% PART 1 & PART 2 Add code here: check if the position <0 and display
% the time when this happens and (PART 2) break out of loop to end simulaiton.
if position(t)<0
lengthOfFlight=time(t) %finds when position is negative i.e. rocket has landed and gets the time at that timestep(t=timestep, time(t)=time in seconds)
break %ends the loop after rocket has landed
end
end
%Add code for PART 3 here. Write a function (named maxHeight.m) which %calculates the max height during the flight. Display the output of the %function in the command window. MaxHeight=maxHeight(position,lengthOfFlight,dt) %gets the max value of position during the flight
%Add code for PART 4 here. Write a function to calculate velocity at impact (kaboomSpeed.m). % Add to the code it outputs the value in command window.
velocityAtImpact=kaboomSpeed(velocity,lengthOfFlight,dt) % gets the value of velocity at the time the rocket crashes
%Add code for PART 9. Add Additonal graphs asked for. Change so the plots finish at %the calcualted endtime from PART 1.
%plot results figure(); plot(time(1:fix(lengthOfFlight/dt)), acceleration(1:fix(lengthOfFlight/dt))) %fix function is used in these to remove floating point error, where numbers that should be integers are not exactly integers title ('Acceleration vs Time - Simple Rocket') xlabel('Time - (s)') ylabel('acceleration - (m/s^2)') grid on
figure(); plot(time(1:fix(lengthOfFlight/dt)), velocity(1:fix(lengthOfFlight/dt))) title ('Velocity vs Time - Simple Rocket') xlabel('Time - (s)') ylabel('velocity - (m/s)') grid on
figure(); plot(time(1:fix(lengthOfFlight/dt)), position(1:fix(lengthOfFlight/dt))) title ('Position vs Time - Simple Rocket') xlabel('Time - (s)') ylabel('Height - (m)') grid on
figure(); plot(time(1:fix(lengthOfFlight/dt)), massFuel(1:fix(lengthOfFlight/dt))) title ('Fuel Mass vs Time - Simple Rocket') xlabel('Time - (s)') ylabel('Fuel Mass - (kg)') grid on
figure(); plot(time(1:fix(lengthOfFlight/dt)), density(1:fix(lengthOfFlight/dt)) ) title ('Density vs Time - Simple Rocket') xlabel('Time - (s)') ylabel('Density - (kg/m^3)') grid on
figure();
plot(position(1:fix(lengthOfFlight/dt)),density(1:fix(lengthOfFlight/dt)) )
title ('Density vs Position - Simple Rocket')
xlabel('Position - (m)')
ylabel('Density - (kg/m^3)')
grid on
figure();
plot(time(1:fix(lengthOfFlight/dt)),abs(drag(1:fix(lengthOfFlight/dt))) )
title ('Drag vs Time - Simple Rocket')
xlabel('Time - (s)')
ylabel('Drag - (N)')
grid on
Also if you know a better way of doing the reading in horserocketoptions feel free to suggest.
This is the contents of horseyRocketOptions:
BF_Rocket,B_F_horse,2000,10000,170000,40,3
Flubber,Derpy,1500,8000,150000,50,2.5
Elsie,Nozomi,1500,7000,130000,60,2
  10 Comments

Sign in to comment.

Accepted Answer

Jan
Jan on 3 Dec 2018
With some guessing:
As far as I understand you want to draw into the same figures in each iteration. Then create the figures before the loop and remember the handles:
for k = 1:7
FigH(k) = figure;
% Set NextPlot is the same as |hold on|:
AxesH(k) = axes('NextPlot', 'add', 'Parent', FigH(k));
end
for k1 = 1:3
for k2 = 1:7
% Plot into k'th axes:
plot(AxesH(k), 1:10, rand(1,10));
end
end
  7 Comments
Jan
Jan on 4 Dec 2018
Edited: Jan on 4 Dec 2018
The first loop must be:
for k =1:7
figH(k)=figure;
% ^^^ This index was missing in your code
axesH= axes('NextPlot','add','Parent',figH(k))
end
Start with solving one step after the other. At first get the code to run before you care about the legends.
You can simplify the sectio for selecting the horse parameters:
index = strcmp({'bfhorse', 'derpy', 'nozomi'}, n);
massEmptyRocket = rocketTable{index,3};
startingMassFuel = rocketTable{index,4};
engineThrust = rocketTable{index,5};
burnTime = rocketTable{index,6};
diameter = rocketTable{index,7};
massHorse = horseTable{index,2};
This let you omit the different if strcmp('bfhorse',n) parts.

Sign in to comment.

More Answers (0)

Categories

Find more on Language Fundamentals in Help Center and File Exchange

Tags

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!