Defining and plotting a piecewise function of irregular interval
13 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Askic V
il 18 Gen 2023
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 Commenti
Più risposte (1)
Jiri Hajek
il 18 Gen 2023
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 Commenti
Vedere anche
Categorie
Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!