I want to input a piecewise function but getting problem in line to that "NOT ENOUGH I/P ARGUMENT"

조회 수: 2 (최근 30일)
The code that I can think of is given bellow
function y=dango(t)
if (-5<=t&t<-4)
y=5+t;
elseif -4<=t&t<=4
y=1;
elseif 4<=t&t<=5;
y=5-t;
else
y=0;
end
t= -6:.01:6;
for i=1:length(t)
y(i)=dango(t(i));
end
plot(t,y)
axis([-6 6 -5 5])
*
| how should I correct it?
Matlab version: 2011b|*

답변 (2개)

Geoff Hayes
Geoff Hayes 2014년 9월 14일

Star Strider
Star Strider 2014년 9월 14일
This one-line if-then-else implementation works, runs without error and seems to produce appropriate output:
dango = @(t) [(-5<=t&t<-4)*(5+t) + (-4<=t&t<=4)*1 + (4<=t&t<=5)*(5-t) + (t>5)*0];
t= -6:.01:6;
for i=1:length(t)
y(i)=dango(t(i));
end
plot(t,y)
axis([-6 6 -5 5])
When I plotted it, there was a ‘glitch’ at 4, but I followed (copy-pasted) your conditions exactly, so perhaps this is the result you intend. If there’s a problem, I’ll let you sort it. One problem might be that in the second and third elements, t<=4 in the second element, and 4<=t in the third element. Mayhap 4<t in the third element would remove the glitch? It did when I made the change and ran the code.
One-line if-then-else statements are really quite efficient. I now make extensive use of them for their efficiency in both coding and execution. They operate on the simple principle that if the associated logic statement evaluates to false=0, they essentially don’t evaluate, but if the associated logic statement evaluates to true=1 they do, and are reported at the output.

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by