Help defining a function or variable

2 visualizzazioni (ultimi 30 giorni)
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

Risposta accettata

Walter Roberson
Walter Roberson il 3 Lug 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.

Più risposte (1)

Michael Hadid
Michael Hadid il 4 Lug 2015
Thank you for your help the program works now.

Categorie

Scopri di più su Programming in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by