Help defining a function or variable

1 vue (au cours des 30 derniers jours)
Michael Hadid
Michael Hadid le 3 Juil 2015
I am writing code for a spring mass damper system and everything looks right compared to the book but I am getting an error "Undefined function or variable 't'." When I define the variable 't' it then goes to give me an error for 'y' and likewise for 'z'. The book does not define any variable so I am left confused on what is wrong. This is my first semester using Matlab and any help would be appreciated.
>> SpringMassDamperProject(t, y, z)
Undefined function or variable 't'.
function y = SpringMassDamperProject(t,y,z)
y = [y(2);-2*z*y(2)-y(1)];
z = [0.1,1.0,5.0];
lintype = char('-k','--k','-.k');
tspan = linspace(0,40,400);
for n = 1:3
[t,y] = ode45(@SpringMassDamperProject,tspan,[1 1]',[],z(n));
figure(1);
plot(t,y(:,1),lintyp(n,:));
hold on
figure(2);
plot(y(:,1),y(:,2),lintyp(n,:));
hold on
end
figure(1)
xlabel('\time');
ylabel('y(\time)');
axis([0,40,-1.5,1.5]);
plot([0,40],[0,0],'k-')
legend('\z=0.1','\z=1.0','\z=5.0')
figure(2)
xlabel('Displacement');
ylabel('Velocity');
legend('\z=0.1','\z=1.0','\z=5.0',2)
axis([-1.5,1.5,-1.5,1.5]);
end

Réponse acceptée

Walter Roberson
Walter Roberson le 3 Juil 2015
Your line
[t,y] = ode45(@SpringMassDamperProject,tspan,[1 1]',[],z(n));
shows that your differential function is named SpringMassDamperProject. But that's the same thing as the name of the function you are already in, according to your code. You would be attempting to have the code call itself.
The function that calculates the derivative must have a different name than the function that calls ode45.
It appears to me that everything from your third line
z = [0.1,1.0,5.0];
onwards should be in a different .m file, and that you should give the name of that new file to run your ode.
function y = SpringMassDamperProject(t,y,z)
y = [y(2);-2*z*y(2)-y(1)];
end
put the above in your SpringMassDamperProject.m file. Then create
function run_SpringMassDamper
z = [0.1,1.0,5.0];
lintype = char('-k','--k','-.k');
tspan = linspace(0,40,400);
for n = 1:3
[t,y] = ode45(@SpringMassDamperProject,tspan,[1 1]',[],z(n));
figure(1);
plot(t,y(:,1),lintyp(n,:));
hold on
figure(2);
plot(y(:,1),y(:,2),lintyp(n,:));
hold on
end
figure(1)
xlabel('\time');
ylabel('y(\time)');
axis([0,40,-1.5,1.5]);
plot([0,40],[0,0],'k-')
legend('\z=0.1','\z=1.0','\z=5.0')
figure(2)
xlabel('Displacement');
ylabel('Velocity');
legend('\z=0.1','\z=1.0','\z=5.0',2)
axis([-1.5,1.5,-1.5,1.5]);
end
and use run_SpringMassDamper to execute the ODE.

Plus de réponses (1)

Michael Hadid
Michael Hadid le 4 Juil 2015
Thank you for your help the program works now.

Catégories

En savoir plus sur Migrate GUIDE Apps dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by