How can I get my script to run properly?

조회 수: 1 (최근 30일)
Aaron
Aaron 2013년 9월 11일
I was initially having trouble with my function, but now since that is running okay, my script is not. It involves a for loop and I'm not sure what I'm doing wrong.
Here is my function file:
function v = piecewise_fun(t)
if 0 <= t & t < 8
v = (10.*t).^2 - (5.*t);
elseif 8 <= t & t < 16
v = 624 - 5.*t;
elseif 16 <= t & t < 26
v = 36.*t + 12.*(t-16).^2;
elseif t >= 26
v = 2136*exp(-0.1.*(t-26));
end
end
And here is what I have for my script file:
t = -5:50
hold on
for i =-5:t % I'm not sure if this is even right!?
v = piecewise_fun(t);
end
plot(v,t)
So, I get the following error:
Undefined function or variable 'v'. Error in piecewise_plot (line 6) plot(v,t)

채택된 답변

Image Analyst
Image Analyst 2013년 9월 11일
편집: Image Analyst 2013년 9월 11일
Not right. Try it this way, in an m-file called aaron.m:
function aaron
t = -5:50
for k = 1 : length(t)
v(k) = piecewise_fun(t(k));
end
plot(t, v, 'b*-', 'LineWidth', 2);
grid on;
xlabel('t', 'FontSize', 30);
ylabel('v', 'FontSize', 30);
title('v vs. t', 'FontSize', 30);
function v = piecewise_fun(t)
v = nan; % Initialize.
if 0 <= t && t < 8
v = (10.*t).^2 - (5.*t);
elseif 8 <= t && t < 16
v = 624 - 5.*t;
elseif 16 <= t && t < 26
v = 36.*t + 12.*(t-16).^2;
elseif t >= 26
v = 2136*exp(-0.1.*(t-26));
end
Both functions are in the same m-file, called aaron.m, or whatever you want just make sure the name is on the first function line.
  댓글 수: 1
Aaron
Aaron 2013년 9월 11일
Thank you! This really helped me out!!

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

추가 답변 (0개)

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by