tags:

views:

86

answers:

3

Below is my code in Matlab I am having trouble with the line sum = (h/2) * (f(a) + f(b)) + h; Matlab says I have to many outputs when I try to call the f(x) function. Is my problem with the f(x) function

function Trapezoid_Uniform(a,b,n)
    h = (b - a)/n;
    sum = (h/2) * (f(a) + f(b)) + h;

    for i = 1:n-1
        x = a + i*h;
        sum = sum + f(x);
    end

    sum = sum*h;
    disp(sum);
end

function f(z)
    f = exp(z);
end
+5  A: 

You need to specify the returned variable in your function. For e.g., In C++ there's an explicit return statement - how does MATLAB know what needs to be returned? You specify it in the signature, i.e. in this case f_of_z.

function f_of_z = f(z)

f_of_z = exp(z);

end
Jacob
+1  A: 

Yes, your problem is in the subfunction: It should return an output (maybe your main function should do that as well);

Instead of

function f(z)
f=exp(z);
end

you should write

function out = f(z)
out = exp(z)
end
Jonas
+1  A: 

I don't have matlab here to test, anyway the code for f should be

function y = f(z)
   y = exp(z);
end
Federico Ramponi

related questions