How to plot a piecewise defined function?

Hi
I want to plot a piecewise defined function. My Problem is, that the plot isn't right and I don't find the mistake... would be great, if somebody could help me!
function CubicSpline
clear all;
clc;
close all;
%CatmullRom:
B1=0;
C1=1/2;
x=-2:.01:2;
y1=zeros(size(x));
if abs(x)< 1,
y1=1/6*((12-(9*B1)-(6*C1))*abs(x).^3 +(-18+(12*B1)+(6*C1))*abs(x).^2 + (6-(2*B1)));
elseif 1 <= abs(x) < 2
y1 = 1/6*(((-B1-6*C1)*abs(x).^3 + (6*B1+30*C1)*abs(x).^2 + (-12*B1-48*C1)*abs(x)+(8*B1+24*C1)));
else y1 = 0;
end
figure(1);clf; hold on;
plot(x,y1,'r')%,x, y2, 'b', x, y3, 'g'
xlabel('X-Axis')
ylabel('Function values')
grid on;
legend({'CatmullRom: B = 0, C = 1/2'},'Location','EastOutside')

5 件のコメント

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 12 月 6 日
Your program is working, what is the expected result?
Simon
Simon 2012 年 12 月 6 日
編集済み: Simon 2012 年 12 月 6 日
If B1 = 0, x = 0, abs(x) is 0 and as consequence the y1 value must be 1. When I plot it the y1-value at x=0 is 2
Jan
Jan 2012 年 12 月 6 日
It is a waste of time to remove all loaded function after starting this function by "clear all". This does not even clean the local workspace, because there are no variables declared before.
Simon
Simon 2012 年 12 月 6 日
Ah, thanks. Your're right!
Simon
Simon 2012 年 12 月 7 日
I still have the problem to plot this function. Could anybody help me? Would be nice :-)

サインインしてコメントする。

回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2012 年 12 月 6 日
編集済み: Andrei Bobrov 2012 年 12 月 6 日

0 投票

B1=0;
C1=1/2;
x0 = -2:.1:2;
x=abs(x0);
y1=zeros(size(x));
t = [x < 1, x >= 1 & x < 2];
y1(t(:,1)) = 1/6*((12-(9*B1)-(6*C1))*x(t(:,1)).^3 +...
(-18+(12*B1)+(6*C1))*x(t(:,1)).^2 + (6-(2*B1)));
y1(t(:,2)) = 1/6*(((-B1-6*C1)*x(t(:,2)).^3 +...
(6*B1+30*C1)*x(t(:,2)).^2 + (-12*B1-48*C1)*x(t(:,2))+(8*B1+24*C1)));
ADD (corrected)
t1 = x0 <= -1;
t2 = x0 > -1 & x0 < 1;
t3 = x0 >= 1;
plot(x0(t1),y1(t1),'r'); hold on
plot(x0(t2),y1(t2),'g');
plot(x0(t3),y1(t3),'k');

6 件のコメント

Simon
Simon 2012 年 12 月 6 日
Hey, thanks! But now I tried to plot y1, but it doesn't work... how can I plot y1?
plot(x, y1(t(:,:,1,2)),'r')
Sry for the stupid question..
Andrei Bobrov
Andrei Bobrov 2012 年 12 月 6 日
see ADD in my answer
Simon
Simon 2012 年 12 月 6 日
The added Code doesn't work :(
plot(x(t(:,1)),y1(t(:,1)),'r',x(t(:,2)),y1(t(:,2)),'g',x(t(:,3)),(t(:,3)),'r');
This doesn't work, too :(
Andrei Bobrov
Andrei Bobrov 2012 年 12 月 6 日
corrected
Simon
Simon 2012 年 12 月 6 日
Hm... there's only a line with the values x=[-2:.1:2] and y=0
Simon
Simon 2012 年 12 月 6 日
It still doesn'´t work. It could not be that difficult to plot this function. Would be great, if somebody could post the right code and explain it to me :)

サインインしてコメントする。

カテゴリ

タグ

質問済み:

2012 年 12 月 6 日

Community Treasure Hunt

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

Start Hunting!

Translated by