Defining and plotting a piecewise function of irregular interval

13 ビュー (過去 30 日間)
RUPAL AGGRAWAL
RUPAL AGGRAWAL 2023 年 1 月 18 日
回答済み: Jiri Hajek 2023 年 1 月 18 日
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

採用された回答

Askic V
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)

その他の回答 (1 件)

Jiri Hajek
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])

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by