Trapezium rule code not work

1 次查看(过去 30 天)
Jack Ellis
Jack Ellis 2019-10-28
编辑: Daniel M 2019-10-28
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 个评论
Jack Ellis
Jack Ellis 2019-10-28
Hi thank you for getting back to me. Ive changed the code to this:
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
y=0;
h=(b-a)/m;
for n=a:h:b
x = a+(n-0.5)*h;
y = y + cos(x)*h;
end
Trapezium_rule=y;
end
It worked when I set a=0, b=pi/2 and m=10. Ive tried changing the value of m to 100 but its telling me that Index in position 1 is invalid. Array indices must be positive integers or logical
values. How do I fix this?
Daniel M
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 CenterFile 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!

Translated by