Trapezium rule code not work

1 Ansicht (letzte 30 Tage)
Jack Ellis
Jack Ellis am 28 Okt. 2019
Bearbeitet: Daniel M am 28 Okt. 2019
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 Kommentare
Jack Ellis
Jack Ellis am 28 Okt. 2019
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 am 28 Okt. 2019
Bearbeitet: Daniel M am 28 Okt. 2019
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

Melden Sie sich an, um zu kommentieren.

Antworten (0)

Kategorien

Mehr zu Introduction to Installation and Licensing finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by