Error in matrix dimension and using a plus sign?

I am trying to write a code for the Midpoint rule given by :
M = \sum_{i=1}^{n}hf(\frac{x_{i-1}+x_{i}}{2})
My MATLAB code is following:
if true
function M = mittpunkt(fun,a,b,n)
h = (b-a)/n;
x = linspace(a,b,n);
f = fun(x);
M = h*(sum(f(((1:n-1)+(1:n))/2)));
end
My error is :
Error using +
Matrix dimensions must agree.
If something is wrong I think it must me the index, certainly not the use of a plus sign, right? Thanks

 채택된 답변

the cyclist
the cyclist 2013년 6월 19일

1 개 추천

In the line where you calculate M, you are trying to add
(1:n-1)
and
(1:n)
which are vectors of two different lengths. Those are the dimensions that don't match.

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2013년 6월 19일
편집: Andrei Bobrov 2013년 6월 19일

1 개 추천

Wikipedia about your problem:
function M = mittpunkt(fun,a,b,n)
h = (b-a)/n;
x = linspace(a,b,n);
f = fun(x);
%M = h*(sum(f(((1:n-1)+(1:n))/2))); your code
M = h*sum(f(1:end-1)+f(2:end))/2; % from Wikipedia
end

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by