我有scilab的问题如何绘制包含if和<like的函数
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
和
function [r]=minus_alpha(t)
r = 1 - alpha(t)
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
来计算y
的每个值,基于t
的值:
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));
如果您觉得答案有用,请不要忘记接受它,以便其他人看到您的问题得到解决。
您可以使用以下代码避免显式循环并提高效率
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
考虑到原始需求中的函数alpha
是分段仿射的,所有提出的答案都过于复杂。在Scilab中可以这样编码:
x = linspace(0,400,1000);
plot(x,linear_interpn(x,[227.8 300],[0.75 0.1]))
即你只需要知道节点坐标(这里是横坐标)和节点处的函数值。功能linear_interpn
也做多线性插值,值得知道它们...
在你的答案之前(谢谢)我的解决方法是由floor和exp(-t ^ 2)组成的指标函数的组合:
function y = alpha(t)
y = floor(exp(-(t .* (t-T1)) / (T1*T1))) * 0.75
+ floor(exp(-((t-T2) .* (t- T1) / (2000)))) .* (2.8-0.009 .* t)
+ floor(exp(-((t-T2) .* (t-1000) / (200000))))*0.1
endfunction