- 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 view (last 30 days)
Show older comments
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 Comments
Daniel M
on 28 Oct 2019
Edited: Daniel M
on 28 Oct 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
Answers (0)
See Also
Categories
Find more on Introduction to Installation and Licensing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!