How can I fix my error and plot the data from the for loop?

The code below is used to calculate the stopping distance between two vehicles. How can I plot the data points from the for loop? Currently, I get an error that says (Undefined function or variable 't').
I would like to plot the v0 values (50-100) on the x-axis, and the distance as the y-axis.
clc
clear all
for v0=50:1:100
% vb=v0b-ab*tb
vb=v0-9*t;
% Calculate the displacement of the [Car B] as a function of time with
% constant acceleration
% sb=s0b+v0b*tb+0.5*ab*t^2
s0b=v0*t;
sb=s0b+v0*tb+0.5*(-9)*t^2;
% Next calculate the velocity of [Car A] as a function of time with constant
% acceleration
% va=v0+aa*ta
va=v0-12*(t-0.75);
% Calculate the displacement of the [Car A] as a function of time with
% constant acceleration
s0a=v0*t;
% sa=s0a+v0*ta+0.5*aa*ta^2
sa=s0a*(0.75)+v0*(t-0.75)+0.5*(-12)*(t-0.75)^2;
% Next calculate the time taken for the moment of closest approach by
% equating the velocity of [Car B] to [Car A]
syms v0 t
eqn1 = v0-9*t == v0-12*(t-0.75);
time=solve(eqn1,t);
% Calculate the minimum distance between the cars to avoid collision by
% equating the displacement of [Car A] and [Car B]
syms v0 time d
eqn2 = d+v0*time-0.5*(9)*time^2==(v0*0.75)+(v0*time)-(v0*0.75)+0.5*(-12)*(time-0.75)^2
distance=solve(eqn2,d)
end

3 Comments

"I get an error that says (Undefined function or variable 't'). "
That means that you have an undefined variable (or function) named 't'.
That's probably happening here: vb=v0-9*t;
In other words, Matlab's asking, "what's t?" It's not defined.
So how would I get rid of that error? I use all of the equations above to calculate 't' near the bottom. t is used to represent time. eqn1 is used to solve for t.
Toward the top of your code you have this line,
vb=v0-9*t;
At that line, t is not defined.
If it's supposed to be defined, then you need to figure out where that value is supposed to come from. Maybe you're mssing some code or mabe you're supposed to load some data.
If 't' isn't supposed to be there, remove it.
Instead of thinking about how to remove the error, think about what your code is supposed to be doing and why it's not doing that. Note that 't' appears in many line before it's defined so the problem is bigger than that 1 line.
For example, you could add t=1 to the top and that would get rid of the error but it probably wouldn't fix the problem. You've got to understand the code, line by line, to understand what's wrong with it.

Answers (0)

This question is closed.

Asked:

on 18 Oct 2020

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!