Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

New to MATLAB?

Error in matrix dimension and using a plus sign?

Asked by Snirisa Gödel

Snirisa Gödel (view profile)

on 19 Jun 2013

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

0 Comments

Snirisa  Gödel

Snirisa Gödel (view profile)

Products

No products are associated with this question.

2 Answers

Answer by the cyclist

the cyclist (view profile)

on 19 Jun 2013
Accepted answer

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.

0 Comments

the cyclist

the cyclist (view profile)

Answer by Andrei Bobrov

Andrei Bobrov (view profile)

on 19 Jun 2013
Edited by Andrei Bobrov

Andrei Bobrov (view profile)

on 19 Jun 2013

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

0 Comments

Andrei Bobrov

Andrei Bobrov (view profile)

Contact us