- Do NOT name any variable with the same name as any function.
- You need to define a variable before it can be added. Given that on the very first loop iteration Trapezium_rule does not exist, what value do you imagine it to have?
Trapezium rule code not work
1 次查看(过去 30 天)
显示 更早的评论
Hi, guys im new to matlab. Ive written a code for the trapezium rule but it wont work becuase Trapezium_rule is undefined. How do I fix it?
function Trapezium_rule=Trapezium_rule(a,b,m)
% in the line Trapezium_rule = Trapezium_rule + cos(x)*h... cos(x) is the equation so change this
% accoriingy
% m is number of increments
%h is increment size
h=(b-a)/m;
for n=a:h:b
x = a+(n-0.5)*h;
Trapezium_rule = Trapezium_rule + cos(x)*h;
end
end
3 个评论
Daniel M
2019-10-28
编辑:Daniel M
2019-10-28
I can reproduce this error if I call this function in the command window like this:
clear
Trapezium_rule = Trapezium_rule(0,pi/2,100); % this works fine
% call it again
Trapezium_rule = Trapezium_rule(0,pi/2,100);
Error: Index in position 1 is invalid. Array indices must be positive integers or logical values.
So, again, as you've already been told, don't name variables after function names.
You're still doing it within your function too (although in this specific case there is no consequence, but it is still bad practice). Here is an improvement
function output = Trapezium_rule(a,b,m)
% in the line Trapezium_rule = Trapezium_rule + cos(x)*h... cos(x) is the equation so change this
% accoriingy
% m is number of increments
%h is increment size
y = 0;
h = (b-a)/m;
for n = a:h:b
x = a+(n-0.5)*h;
y = y + cos(x)*h;
end
output = y;
end
回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Introduction to Installation and Licensing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!