I get error using plot, vectors must be same lengths and error in midpt (line 27), plot (x,If)? Integral code works fine, was just trying to plot a graph too..

1 view (last 30 days)
Here's my code:
function [ area ] = midpt ( f,xl,xu,dx )
%area will be total area under integration curve
%using midpoint rule
%will also plot function and integral curves
%f is the function to integrate
%xl is the lower limit of integration
%xu is the upper limit of integration
num=(xu-xl)/dx;
a=xl;
x=xl:dx:xu;
M=0;
If=0;
for ii=1:1:num
b=a+dx;
M(ii)=(b-a)*f((a+b)/2);
If(ii)=sum(M);
a=b;
end
plot(x,If)
area=sum(M);
end

Accepted Answer

Geoff Hayes
Geoff Hayes on 16 Jan 2015
Thomas - the error is telling you that your x and If vectors are of different lengths and so cannot be plotted against each other. If you put a breakpoint at this line, you will be able to check the size of each. When I do this, calling the function as
func = @(x)x^2;
midpt(func,1,100,1)
I notice that x is a vector of 100 elements, whereas If is a vector of 99 elements. Remember that you will have (for example) 100 elements that make up the upper and lower bounds of the 99 rectangles, so you can't possible plot one versus the other. Hence the error.
Please describe what you are attempting to do with this plot. Why try to plot the summed areas? What are you trying to show?
As well, please look closer at your midpoint algorithm as I don't think that it is quite correct (you may be missing the 1/num factor).

More Answers (0)

Community Treasure Hunt

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

Start Hunting!