Trying to plot a function of time while a variable changes values at different time intervals

1 次查看(过去 30 天)
As the title states I'm trying to plot a function (or two actually), while a variable changes at different variables. The program just continues to run and doesn't actually stop so it's stuck somewhere and I can't figure out where. Also would this work once it's able to complete? I don't like having the beta inside the loop, but get an error whiles outside.
clear all
clc
L_phi = -2.729;
L_sigma_a = -43.692;
lambda = L_phi;
tau = 1/L_phi;
t = [0:0.01:5];
for t <= 5
if t < 2.5
sigma_a = -3;
elseif t >=2.5
sigma_a = 0;
for beta = (L_sigma_a/L_phi).*sigma_a;
phidot = beta.*(1-exp(lambda.*t));
phi = beta.*(t-1/tau.*exp(tau.*t));
end
end
end
figure(1)
plot(t,phidot)
title('phidot vs time')
xlabel('seconds')
ylabel('degrees')
figure(2)
plot(t, phi)
title('phi vs time')
xlabel('seconds')
ylabel('degrees')
Unrecognized function or variable 'phidot'.
Error in HW1MAE503 (line 23)
plot(t,phidot)

回答(1 个)

Harshavardhan
Harshavardhan 2025-6-26
The main issue in your code comes from how the “for loops are structured and how variables are assigned inside them. In MATLAB, a for loop iterates over a vector of indices or values, and you need to preallocate your result arrays to store values at each time step. Also, the assignments to phidot and phi should be made inside the loop for each time value.
To fix this:
  • Use a for loop to iterate over the indices of your time vector.
  • Preallocate your result arrays (phidot and phi) before the loop.
  • Assign values to each element of these arrays inside the loop using the current time value.
Here is the updated “for” loop code:
% Preallocate result arrays
phidot = zeros(size(t));
phi = zeros(size(t));
for i = 1:length(t)
ti = t(i);
% Determine sigma_a based on time
if ti < 2.5
sigma_a = -3;
else
sigma_a = 0;
end
% Calculate beta for this time
beta = (L_sigma_a / L_phi) * sigma_a;
% Calculate phidot and phi for this time
phidot(i) = beta * (1 - exp(lambda * ti));
phi(i) = beta * (ti - (1/tau) * exp(tau * ti));
end
For more information on “zeros” and ”for” refer to their respective links below:

类别

Help CenterFile Exchange 中查找有关 Historical Contests 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by