【问题标题】:Plotting own function in scilab在scilab中绘制自己的函数
【发布时间】:2014-11-12 21:35:29
【问题描述】:
嘿,我在 scilab 中绘制自己的函数时遇到了问题。
我想绘制以下函数
function f = test(n)
if n < 0 then
f(n) = 0;
elseif n <= 1 & n >= 0 then
f(n) = sin((%pi * n)/2);
else
f(n) = 1;
end
endfunction
后跟控制台命令
x = [-2:0.1:2];
plot(x, test(x));
我加载了函数并得到以下错误
!--错误 21
无效索引。
在函数 lala 的第 7 行调用:
绘图(x,测试(x))
你能告诉我如何解决这个问题
【问题讨论】:
标签:
matlab
function
plot
scilab
【解决方案1】:
所以我现在用 for 循环做到了。我认为这不是最好的解决方案,但我无法让其他解决方案运行 atm...
function f = test(n)
f = zeros(size(n));
t = length(n);
for i = 1:t
if n(i) < 0 then
f(i) = 0;
elseif n(i) <= 1 & n(i) >= 0
f(i) = sin((%pi * n(i)/2));
elseif n(i) > 1 then
f(i) = 1;
end
end
endfunction
我想我需要找到有关此问题的来源并习惯使用 matlab/scilab 必须完成的功能和特权 :)
谢谢你的帮助
【解决方案2】:
原罪是
function f = test(n)
(...)
f(n) = (...)
(...)
endfunction
f 应该是函数的结果。因此,f(n) 不是“函数test 接受参数n 的值”,而是“f 的n-th 元素”。然后,Scilab 会尽其所能地处理这个问题;在您的测试用例中,它会尝试访问非整数索引,这会导致错误。您的循环解决方案解决了问题。
在您的第一个公式中将所有三个f(n) 替换为f 使其成为可行的东西......只要参数是标量(而不是数组)。
如果您希望test 能够在不进行循环的情况下接受向量参数,那么问题在于n < 0 是一个与n 大小相同的向量。我的解决方案将使用逻辑数组来索引三个条件中的每一个:
function f = test(n)
f = zeros(size(n));
negative = (n<0);//parentheses are optional, but I like them for readability
greater_than_1 = (n>1);
others = ~negative & ~greater_than_1;
f(isnegative)=0;
f(greater_than_1)=1;
f(others) = sin(%pi/2*n(others));
endfunction