How to plot a linear piecewise function on matlab?

3 次查看(过去 30 天)
Can you please mark the error in the following code?
I'm facing the error:
>> linear
Linear Function:
Parameters: [1x1 struct]
X = 0:0.001:50 ;
f = double(X<20).* (0) + ...
double(and(X>=20,X<35)).* ((X-20)./15) + ...
double(X>=35).*(1);
g = double(X<20).* (1) + ...
double(and(X>=20,X<35)).* ((35-(X))./(15)) + ...
double(X>=35).*(0);
figure;
plot(X,f,'r','linewidth',2);
hold on ;
plot(X,g,'b','linewidth',2);
xlabel('X');
xticks(2:1:10);
  3 个评论
Dyuman Joshi
Dyuman Joshi 2023-6-26
The code expect for the first line you mentioned runs without any error. I am not sure what the command linear supposed to do, nor do we have the data of linear to run to reproduce the error.
If you are getting an error, copy and paste the full error, which means all of the red text.
Also, there's no need of using double().
X = 0:0.001:50 ;
f = (X<20).* (0) + (and(X>=20,X<35)).* ((X-20)./15) + (X>=35).*(1);
g = (X<20).* (1) + (and(X>=20,X<35)).* ((35-(X))./(15)) + (X>=35).*(0);
figure;
plot(X,f,'r','linewidth',2);
hold on ;
plot(X,g,'b','linewidth',2);
xlabel('X');
%xticks(2:1:10);
DGM
DGM 2023-6-26
... or just
% all you need to define a polyline are the vertices
x = [0 20 35 50];
f = [0 0 1 1];
g = [1 1 0 0];
plot(x,f,'r','linewidth',2);
hold on ;
plot(x,g,'b','linewidth',2);
xlabel('X');

请先登录,再进行评论。

回答(1 个)

Sam Chak
Sam Chak 2023-6-26
Might as well...
but this approach requires the fuzzy logic toolbox.
x = 0:0.1:50;
f = linsmf(x, [20 35]); % s-shaped function
g = linzmf(x, [20 35]); % z-shaped function
plot(x, [g; f]', 'linewidth', 2), grid on
xlabel('X');

类别

Help CenterFile Exchange 中查找有关 2-D and 3-D Plots 的更多信息

产品


版本

R2014b

Community Treasure Hunt

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

Start Hunting!

Translated by