我想编写一个近似积分与梯形规则的函数。
我首先在一个文件中定义了一个函数:
<html>
<head>
<script>
var f__inputs = [];
document.addEventListener('DOMContentLoaded', function () {
f__init();
}, false);
function f__init(){
f__inputs = document.body.getElementsByClassName("superinput");
console.log(f__inputs);
f__insert();
}
function f__insert(){
for(var i=0;i<f__inputs.length;i++){
f__inputs[i].id = "superinput-wrapper-" + i;
f__inputs[i].className = "superinput-wrapper";
var d = f__inputs[i].getAttribute("data-fields");
for(var j=0;j<d;j++){
var input = document.createElement("input");
input.setAttribute("data-wrap",i);
input.setAttribute("data-pos",j);
input.setAttribute("size","1");
input.setAttribute("type","text");
input.id = "superinput-input-" + j;
input.className = "superinput-input";
if(j!=0){
input.setAttribute("disabled","true");
input.disabled = true;
}
f__inputs[i].appendChild(input);
}
}
}
</script>
</head>
<body>
<p>
<b>Task 90.</b>
Lorem ipsum dolor sit amet...
<div class="superinput" data-fields="6"></div>
</p>
<p>
<b>Task 91.</b>
Lorem ipsum dolor sit amet...
<div class="superinput" data-fields="6"></div>
</p>
<p>
<b>Task 91.</b>
Lorem ipsum dolor sit amet...
<div class="superinput" data-fields="6"></div>
</p>
</body>
</html>
然后我写了我的函数,用近似的下限a和上限b(也在另一个文件中)近似定积分:
function[y] = integrand(x)
y = x*exp(-x^2); %This will be integrand I want to approximate
end
但是当我想从命令窗口调用此函数时,例如使用function [result] = trapez(integrand,a,b,k)
sum = 0;
h = (b-a)/k; %split up the interval in equidistant spaces
for j = 1:k
x_j = a + j*h; %this are the points in the interval
sum = sum + ((x_j - x_(j-1))/2) * (integrand(x_(j-1)) + integrand(x_j));
end
result = sum
end
,我总是会收到错误'没有足够的输入参数'。我不知道我做错了什么?
答案 0 :(得分:2)
您的代码存在许多问题:
x_(j-1)
未定义,并且实际上不是有效的Matlab语法(假设您希望它是变量)。trapez(integrand,0,1,10)
,您实际上在没有输入参数的情况下调用integrand
函数。如果要传递句柄,请改用@integrand
。但在这种情况下,根本不需要通过它。sum
。如果您还尝试使用sum
作为函数,这很容易导致难以调试的问题。 这是一个有效的版本(注意还有更好的代码风格):
function res = trapez(a, b, k)
res = 0;
h = (b-a)/k; % split up the interval in equidistant spaces
for j = 1:k
x_j1 = a + (j-1)*h;
x_j = a + j*h; % this are the points in the interval
res = res+ ((x_j - x_j1)/2) * (integrand(x_j1) + integrand(x_j));
end
end
function y = integrand(x)
y = x*exp(-x^2); % This will be integrand I want to approximate
end
调用它的方式是:result = trapez(0, 1, 10);
答案 1 :(得分:0)
您的<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="SideMenu" class="SideMenu1">
<a href="javascript:void(0)" class="XButton" onclick="closeNav()">×</a>
<a href="#" id="link1">Link1</a><br>
<a href="#">Link2</a><br>
<a href="#">Link3</a><br>
<a href="#">Link4</a><br>
</div>
<span class="woosh">Woosh</span> <!This is the Open button!>
函数需要输入参数integrand
,您在命令行函数调用中未提供该参数