Clear Filters
Clear Filters

How can I pass in variables into fsolve()?

9 views (last 30 days)
Say I have some matrix 3x3 matrix, A, that is defined as:
for ii = 1:length(layers+1)
A(ii) = [k0^2*eO(ii)-ky^2-kz^2,k0^2*eH(ii)+kx*ky,kx*kz;
kx*ky-k0^2*eH(ii),k0^2*eO(ii)-kx^2-kz^2,ky*kz;
kx*kz,ky*kz,k0^2*eE(ii)-kx^2-ky^2];
end
I am defining every variable in this matrix except for "kz". I'm trying to solve where the determinant of A is equal to zero. The catch is i don't want to use some variation of:
syms kz
kz = solve(det(A) == 0,kz);
because this is a function that is called several hundred thousand times through my main code and I would like to avoid using syms as it is slow.
Now, I've read up on a function called fsolve() and can't seem to figure out how to pass in the known variables of A to this section of code:
fun = @det0
x0 = zeros(4,1);
kz = fsolve(fun,x0);
function F = det0(kz)
F = det([k0^2*eO-ky^2-kz^2,k0^2*eH+kx*ky,kx*kz;
kx*ky-k0^2*eH,k0^2*eO-kx^2-kz^2,ky*kz;
kx*kz,ky*kz,k0^2*eE-kx^2-ky^2]);
Let me know if you need more information to help solve this problem. Thanks!
  1 Comment
Morgan Blankenship
Morgan Blankenship on 25 Oct 2019
Or if there is another method of solving for an unknown variable without using syms, that will help too.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 25 Oct 2019
Edited: Stephen23 on 25 Oct 2019
"...can't seem to figure out how to pass in the known variables of A to this section of code:"
The MATLAB documentation explains how:
Simply define your function with all of the required inputs:
function F = myfun(k0,kx,ky,kz,eE,eH,eO)
M = [k0^2*eO-ky^2-kz^2, k0^2*eH+kx*ky, kx*kz;
kx*ky-k0^2*eH, k0^2*eO-kx^2-kz^2, ky*kz;
kx*kz, ky*kz, k0^2*eE-kx^2-ky^2];
F = det(M);
end
And then use an anonymous function with fzero:
>> k0 = 1.1;
>> kx = 1.2;
>> ky = 1.3;
>> eE = 1.4;
>> eH = 1.5;
>> eO = 1.6;
>> fun = @(kz)myfun(k0,kx,ky,kz,eE,eH,eO);
>> kz = fzero(fun,pi)
kz =
0.51807
Check the function value is zero (within floating point tolerances):
>> fun(kz)
ans =
1.4664e-16

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!