简体   繁体   中英

Octave integrating

I have some problems with integrating in Octave. I have the following code:

a=3;

function y = f (x)
y = x*x*a;

endfunction

[v,ier,nfun,err]=quad("f",0,3);

That 'a' in function is giving me troubles. Octave says that 'a' is undefined. So, if I instead of 'a' put number 3 in function y everything works just fine. However, I want to have 'a' in function so I can change it's value.. How do I do that?

Thanks

You could use a function closure, which will encapsulate the a .

function f = makefun (a)
    f = @(x) x * x * a;
endfunction

f = makefun(3)

[v, ier, nfun, err] = quad(f, 0, 3);

There are two main options.

Option 1 is, as voithos notes, make 'a' an input to the function.

Option 2 is to define 'a' to be a global variable.

global a=3;

function y = f (x)
 global a
 y = x*x*a;

endfunction

[v,ier,nfun,err]=quad("f",0,3);

This will cause 'a' to be the same value inside and outside the function.

Your function is actually dependent on two values, x and a, therefor:

f=@(x,a) x*x*a
[V, IER, NFUN, ERR] = quad (@(x) f(x,3), A, B, TOL, SING)

I used inline functions as i think it is easier to understand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM