2
$\begingroup$

Okay so I'm doing numerical integration using the trapezoid rule. I wrote the m file as such:

function y = trap(f,a,b,N)  
h= (b-a)/N; y=0;  
for i=1: N-1  
    x=(a+i*h);y=y+eval(f);  
end  
y=2*y; x=a; y=y+eval(f); x=b; y=y+eval(f);  
y= (h/2)*y;  

It says that the value assigned to x might be unused and I don't know why. If someone could tell me what I am doing wrong that would be awesome.

$\endgroup$
  • 1
    $\begingroup$ I don't know Matlb, but it seems you need to feed $x$ to $f$ somehow. Is $x$ local to this function? $\endgroup$ – Ross Millikan Dec 8 '15 at 23:59
  • $\begingroup$ Also try and avoid for-loops in Matlab if you can. They are very slow. $\endgroup$ – mathreadler Dec 9 '15 at 9:17
1
$\begingroup$

You need to pass $x$ into the function $f$ for evaluation; MATLAB is giving you the "X may not be used" warning because $x$ is changing in every loop without ever being passed into $f$

I have made a couple changes to the code (for readability, changing eval to feval...)

function y = trap(f,a,b,N)  
h = (b-a)/(N);
y=0;
for i=1:N-1
    x=(a+i*h);
    y=y+feval(f,x);
end
y = y+feval(f,a)+feval(f,b)
y = h*y;
| cite | improve this answer | |
$\endgroup$
1
$\begingroup$

I'm assuming everything else is OK, just considering performance in Matlab. If (1:N-1) is many values you will be much better off storing the vector than using a for loop.

function y = trap(f,a,b,N)  
h = (b-a)/(N);
y=0;
% Instead of a for loop we make a vector v storing the values (1,2,...N-1):
v = 1:N-1;
x = (a+v*h);
y = sum(feval(f,x));

y = y+feval(f,a)+feval(f,b); 
y = h*y;

Avoiding for-loops can easily give a speed up of 100-1000 times or more. Maybe it doesn't matter right now, but it will start mattering once you build more advanced and useful stuff.


Edit As mentioned by costrom in the comments : The above assumes that function f can take an array of inputs. If it can not do so, we can still replace the line

y = sum(feval(f,x));

with

y = sum(arrayfun(f,x));

for example the function

f = @(x) x^2;

feval(f,x);

will give error if x is a vector , but the following will work:

arrayfun(f,x);

| cite | improve this answer | |
$\endgroup$
  • $\begingroup$ you can combine the endpoints of the integration by changing v to 0:N. the implementation in the answer will work much faster than OP, but with the caveat that the function f has to be able to accept a vector of $x$ $\endgroup$ – costrom Dec 9 '15 at 17:10
  • $\begingroup$ yes and if it does not accept a vector we can do an arrayfun. $\endgroup$ – mathreadler Dec 9 '15 at 17:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.