2
votes

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

2
I see a problem that you use matrix division instead element-wise in function funk - Danil Asotsky
THANK YOU! It works perfect now, wasn't the first time I forgot the dots I have to admit but I will be more careful in the future! - Nekroz

2 Answers

3
votes

@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

3
votes

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'.