captain
captain

Reputation: 1827

Why does my function return two values when I only return one?

So I'm trying to implement the Simpson method in Matlab, this is my code:

function q = simpson(x,f)
n = size(x);
%subtracting the last value of the x vector with the first one
ba = x(n) - x(1);

%adding all the values of the f vector which are in even places starting from f(2)
a = 2*f(2:2:end-1);
%adding all the values of the f vector which are in odd places starting from 1
b = 4*f(1:2:end-1);

%the result is the Simpson approximation of the values given
q = ((ba)/3*n)*(f(1) + f(n) + a + b);

This is the error I'm getting:

Error using ==> mtimes
Inner matrix dimensions must agree.

For some reason even if I set q to be

q = f(n)

As a result I get:

q =

 0     1

Instead of

q =

 0 

When I set q to be

q = f(1)

I get:

q =

 0


q =

 0

I can't explain this behavior, that's probably why I get the error mentioned above. So why does q have two values instead of one?

edit: x = linspace(0,pi/2,12); f = sin(x);

Upvotes: 0

Views: 75

Answers (1)

nivag
nivag

Reputation: 573

size(x) returns the size of the array. This will be a vector with all the dimensions of the matrix. There must be at least two dimensions.

In your case n=size(x) will give n=[N, 1], not just the length of the array as you desire. This will mean than ba will have 2 elements.

You can fix this be using length(x) which returns the longest dimension rather than size (or numel(x) or size(x, 1) or 2 depending on how x is defined which returns only the numbered dimension).

Also you want to sum over in a and b whereas now you just create an vector with these elements in. try changing it to a=2*sum(f(...)) and similar for b.

The error occurs because you are doing matrix multiplication of two vectors with different dimensions which isn't allowed. If you change the code all the values should be scalars so it should work.

To get the correct answer (3*n) should also be in brackets as matlab doesn't prefer between / and * (http://uk.mathworks.com/help/matlab/matlab_prog/operator-precedence.html). Your version does (ba/3)*n which is wrong.

Upvotes: 3

Related Questions