Reputation: 158
Let's say I have a function like f(x)=x+y
, and I want to integrate with respect to x and leave y
as is. In Mathematica I can just put in Integrate[x+y, {x,0,3}]
but in Octave when I try the code below I get the error,
error: quad: evaluation of user-supplied function failed
error: called from
f at line 2 column 5
octave-test.m at line 4 column 21
Code:
function g = f(x)
g = x+y;
endfunction
[q, ier, nfun, err] = quad('f',0,3)
So how can I have a variable in there and get an output of 9/2+3y
, which is the answer to that integral?
Upvotes: 1
Views: 310
Reputation: 60660
quad
does numerical integration, it will never give you a result with a y
variable in it, the result will always be a number.
You are attempting to do symbolic math. You need the symbolic package. I found this link for how to install his package. Then the following code will do as you want:
pkg load symbolic % do this once for the session.
syms x y
f = x + y;
F = int(f, x, 0, 3)
Upvotes: 1
Reputation: 2688
y
is undefined in the code of your function f(x)
. Although you don't show it, I assume that y
is global variable, but Octave function can't access the global variables. A solution is to define an inline function, as they access the global variables.
f = @(x) x+y;
[q, ier, nfun, err] = quad('f',0,3)
More generally, if you already have a multi-variable function multifunc(x,y,z)
and need to provide a univariable function with the other variables fixed, you define:
f = @(x) multifunc(x,y,z);
[q, ier, nfun, err] = quad('f',0,3)
IMPORTANT: you have to define the inline function just before it is used, as it takes the fixed variables as they are at the moment you define it, and is not updated if the fixed variables change. See:
>> y=3;
>> f = @(x) x+y;
>> f(5)
ans = 8
>> y=10;
>> f(5)
ans = 8
>> f = @(x) x+y;
>> f(5)
ans = 15
Upvotes: 2