필터 지우기
필터 지우기

M-file function

조회 수: 4 (최근 30일)
zoelle wong
zoelle wong 2019년 1월 30일
편집: Guillaume 2019년 1월 30일
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

채택된 답변

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

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by