Defining and plotting a piecewise function of irregular interval
13 次查看(过去 30 天)
显示 更早的评论
I want to plot a piecewise function of different interval lengths. I have tried 3 syntaxes and none are working, Kindly resolve the issue. Thank you in advance.
Syntax 1
clc; close all;
x1 = linspace(0,1/4,10); y1 = 1;
x2 = linspace(1/4,1/2,10); y2 = 4*(x2).^2;
x3 = linspace(1/2,3/4,10); y3 = 8*(x3).^2 - 4*(x3) + 2 ;
x4 = linspace(3/4,1,10); y4 = (32/3)*(x4).^3 - 16*(x4).^2 -14*(x4) - (5/2) ;
plot([x1,x2,x3,x4],[y1,y2,y3,y4])
Syntax 2
x1=x(0<=x & x<1/4);
y(0<=x & x<1/4)=1;
x2=x(1/4<=x & x<1/2);
y(1/4<=x & x<1/2)=4*(x2);
x3=x(1/2<=x & x<3/4);
y(1/2<=x & x<3/4)= 8*(x3).^2 - 4*(x3) + 2;
x4=x(3/4<=x & x<1);
y(x4)= (32/3)*(x4).^3 - 16*(x4).^2 -14*(x4) - (5/2);
x=linspace(0,1,100);
y = piecewise([x1, x2, x3, x4]);
plot(x,y)
Syntax 3
x = linspace(0,1,100);
for i = 1:10;
if x(i)>=0 & x(i)<1/4;
y(i)=1;
elseif x(i)>=1/4 & x(i)<1/2;
y(i)=4*x(i);
elseif x(i)>=1/2 & x(i)<3/4;
y(i)= 8*x(i)^2 - 4*x(i) + 2;
else x(i)>=3/4 & x(i)<1;
y(i)= (32/3)*x(i)^3 - 16*x(i)^2 -14*x(i) - (5/2) ;
end
end
0 个评论
采纳的回答
Askic V
2023-1-18
You can try something like this:
syms x %makes x a symbolic variable
f = piecewise(x>=0 & x<1/4, 1, x>=1/4 & x<1/2, 4*x.^2, x>=1/2 & x<3/4, 8*x.^2-4*x+2,...
x>=3/4 & x<1, (32/3)*x.^3 - 16*x.^2-14*x-5/2);
fplot(f)
0 个评论
更多回答(1 个)
Jiri Hajek
2023-1-18
Hi, you need to check your code... In your first syntax, you have a size mismatch of x1 and y1. You may use the "ones" function to make it work:
clc; close all;
x1 = linspace(0,1/4,10); y1 = ones(size(x1));
x2 = linspace(1/4,1/2,10); y2 = 4*(x2).^2;
x3 = linspace(1/2,3/4,10); y3 = 8*(x3).^2 - 4*(x3) + 2 ;
x4 = linspace(3/4,1,10); y4 = (32/3)*(x4).^3 - 16*(x4).^2 -14*(x4) - (5/2) ;
plot([x1,x2,x3,x4],[y1,y2,y3,y4])
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!