Borrar filtros
Borrar filtros

M-file function

4 visualizaciones (últimos 30 días)
zoelle wong
zoelle wong el 30 de En. de 2019
Editada: Guillaume el 30 de En. de 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

Respuesta aceptada

Mark Sherstan
Mark Sherstan el 30 de En. de 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 comentario
zoelle wong
zoelle wong el 30 de En. de 2019
Oooh! Ok thank you so much! That clears up a lot of things. Thank you:)

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Programming en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by