Defining and plotting a piecewise function of irregular interval

조회 수: 9 (최근 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 CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by