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 Center および File ExchangeIntroduction 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