Filter löschen
Filter löschen

M-file function

4 Ansichten (letzte 30 Tage)
zoelle wong
zoelle wong am 30 Jan. 2019
Bearbeitet: Guillaume am 30 Jan. 2019
Hello!
I am writing an Mfile script that calls a Mfile function to evaluate v(t). v(t) is given as a piecewise function and I have to use if-elseif logic structures for all points of t. My script should use this function and evelop a plot of v versus t for t = -5 to t =50 using a stepize of .25.
When I run my code, I found that my if-elseif logic structures are correct, however I get the message: "Out of memory. The likely cause is an infinite recursion within the program." on line 20 when I attempt to plot my function.
%Part A: Mfile function to compute v as a function of t
function v = vPieceWise(t)
if (t < 0)
v = 0;
elseif (0 <= t)&&(8<=16)
v = -5*t+10*t.^2;
elseif (8<=16)&&(t<=16)
v = 624 - 3*t;
elseif (t<=16)&&(t<=26)
v = 12*(t-16).^2+36*t;
elseif (26<t)
v = 2136*exp(-0.1*(t-26));
end
%creating window of plot from -5 to 50 using stepsize 0.25 for t x-axis
%t should be on the x axis, v should be on the y axis
k=0;
for i= -5:.25:50
k = k+1;
t(k)=i;
v(k)=vPieceWise(t(k));
end
plot(t,v);
figure
plot(t,v);
hold on
end

Akzeptierte Antwort

Mark Sherstan
Mark Sherstan am 30 Jan. 2019
Your function is calling itself without approaching any convergance or something that will allow it to end. Therefore it will run forever and eventually out of memory (hence the error). Try splitting it up into a script and a function as so:
Script:
%creating window of plot from -5 to 50 using stepsize 0.25 for t x-axis
%t should be on the x axis, v should be on the y axis
k=0;
for i= -5:.25:50
k = k+1;
t(k)=i;
v(k)=vPieceWise(t(k));
end
plot(t,v);
figure
plot(t,v);
hold on
Function:
%Part A: Mfile function to compute v as a function of t
function v = vPieceWise(t)
if (t < 0)
v = 0;
elseif (0 <= t)&&(8<=16)
v = -5*t+10*t.^2;
elseif (8<=16)&&(t<=16)
v = 624 - 3*t;
elseif (t<=16)&&(t<=26)
v = 12*(t-16).^2+36*t;
elseif (26<t)
v = 2136*exp(-0.1*(t-26));
end
  1 Kommentar
zoelle wong
zoelle wong am 30 Jan. 2019
Oooh! Ok thank you so much! That clears up a lot of things. Thank you:)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Programming finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by