Function 带if的Scilab绘图函数
我在scilab有个问题 如何绘制包含if和Function 带if的Scilab绘图函数,function,plot,interpolation,scilab,piecewise,Function,Plot,Interpolation,Scilab,Piecewise,我在scilab有个问题 如何绘制包含if和
function y = alpha(t)
if (t < 227.8) then
y = 0.75;
elseif (t < 300) then
y = 2.8 - 0.009 .* t;
else
y = 0.1;
end
endfunction
当我使用
x = linspace(0,300)
plot(x, alpha(x))
我收到了错误信息
WARNING: Transposing row vector X to get compatible dimensions
plot2d: falsche Größe für Eingangsargument: inkompatible Größen.
Error 999 : in plot2d called by plot
对不起,德国混音。谢谢。如果您检查
alpha(x)
的输出,您将看到它只是一个标量(而不是向量)。我想你想要这样的东西,所以有必要遍历t
,根据t
的值计算y
的每个值:
clc;
clear;
function y = alpha(t)
for i=1:size(t,"*")
if t(i) < 227.8 then
y(i) = 0.75;
elseif t(i) < 300 then
y(i) = 2.8 - 0.009 * t(i);
else
y(i) = 0.1;
end
end
endfunction
x = linspace(0,300);
plot2d(x,alpha(x));
clc;
清楚的
函数y=α(t)
对于i=1:尺寸(t,“*”)
如果t(i)<227.8,则
y(i)=0.75;
否则t(i)<300
y(i)=2.8-0.009*t(i);
其他的
y(i)=0.1;
结束
结束
端功能
x=linspace(0300);
plot2d(x,alpha(x));
如果您觉得答案有用,请不要忘记接受它,这样其他人就会看到您的问题已经解决。您可以避免显式循环,并使用下面的代码更高效
function y = alpha(t)
y=0.1*ones(t);
y(t<227.8)=0.75;
i=t>=227.8&t<300;
y(i)=2.8 - 0.009 .* t(i);
endfunction
函数y=alpha(t)
y=0.1*个(t);
y(t=227.8&t在您回答之前(谢谢),我的解决方法是将由floor和exp(-t^2)组成的指示器功能组合在一起:
看到绝大多数Scilab社区不知道矢量化操作,真是令人难过。您可以将功能更改为:
function y = alpha(t)
y = 0.1;
if t < 227.8 then
y = 0.75;
elseif t < 300 then
y = 2.8 - 0.009 * t;
end
y = 1 - y;
endfunction
其结果是:
经验法则如果您使用for循环,您需要修改代码,如果有人向您提供不需要for循环的代码,您可能不应该使用它。考虑到原始需求中的函数alpha
是分段仿射的,所有建议的答案都过于复杂。在Scilab中,可以将帽沿:
x = linspace(0,400,1000);
plot(x,linear_interpn(x,[227.8 300],[0.75 0.1]))
i、 e.您只需知道节点坐标(此处为横坐标)函数linear\u interpn
也做多重线性插值,值得一提的是…使用feval
不是真正的矢量化,因为这里它重复调用alpha
,尽管函数本身可以使用点运算符进行矢量化。@Stéphanemotelet好吧,我已经详细地解释了我所说的向量化这个术语。这是我从Python术语中借用的东西,用来指列表理解和操作,以消除对过多for循环的需要。这不是并行性,只是一种使代码更加一致的方法。
function y = alpha(t)
y = 0.1;
if t < 227.8 then
y = 0.75;
elseif t < 300 then
y = 2.8 - 0.009 * t;
end
y = 1 - y;
endfunction
x = linspace(0, 300);
plot2d(x, feval(x, alpha));
x = linspace(0,400,1000);
plot(x,linear_interpn(x,[227.8 300],[0.75 0.1]))