Question

I've written a program in Matlab which purpose is to calculate the integral of a certain function. I'm supposed to use the trapezoidal method for the integral. At the moment, the code looks like this:

a=0; b=2.5; n=2; % n is the number of intervals
h=(b-a)/n; %the width of every interval
x=a:h:b
y=labb2uppg1Funkfil(x)
trapets=h*(sum(y)-(y(1)+y(length(y)))/2)
plot(x,y) 

% This is located in a different file named labb2uppg1Funkfil
function y = funk(x)
y = exp(-x/3)/(2-cos(pi*x));

I think the problem is that my function only returns a single value of y when it's supposed to be some more! How can I rewrite the function to return multiple values? Or is it something else that's wrong here?

Thanks in advance! end

Was it helpful?

Solution

@DanilAsotsky is Rigth. If you want the function to return a y for every x you insert you should rewrite the function to make elementwise operations

function y = funk(x)
y = exp(-x./3)./(2-cos(pi.*x));

Would do the work

OTHER TIPS

You need to use element-wise division (./) instead of matrix division (/). Documentation here.

y = exp(-x/3) ./ (2-cos(pi*x));

Also note that it's highly recommended for the function and filename to be the same. Both should be 'labb2uppg1Funkfil' or 'funk'.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top