MATLAB: CODE ASSISTANCE

eigen valueequationsfunctionfzero

Hi, I have the following code ,but it gives an error. The code is :
function lambda = drive_zr17t9(p)
format short e;
load saved_data;
theta = pi/2;
zeta = cos(theta);
I = eye(n,n);
Q = zeta*I-p*p';
%T is a matrix(5,5)
Mroot = M.^(1/2); %optimization

T = Mroot*Q*Mroot;
%find the eigen values
E = eig(T);
%find the negative eigen values -- this section still needs to be fixed
ind = find(E<0);
G = E(ind);
%find the smallest negative eigen value
gamma = min(abs(G)); %this is almost certainly wrong!
%now solve for lambda
bounds = sort([0, -1/gamma]); %in case gamma is positive
Minv = inv(M); %optimization
lambda = fzero(@(lambda) zr17t9(lambda, Minv, Q, zm), bounds); %do the searching

end
function r = zr17t9(lambda, Minv, Q, zm)
Winv = inv(mInv+lambda.*Q);
r = -ctranspose(zm)*Minv*Winv*Q*Winv*Minv*zm;
end
_*The error is :
??? Error using ==> fzero
FZERO cannot continue because user supplied function_handle ==> @(lambda) zr17t9(lambda, Minv, Q, zm)
failed with the error below.
Variable 'zm' is used as a command function.
Error in ==> drive_zr17t901 at 21
lambda = fzero(@(lambda) zr17t9(lambda, Minv, Q, zm), bounds); %do the searching
_*

Best Answer

Remove the final "end" statement from drive_zr17t9 and the code would likely start working.
This is a side effect of "poofing variables into existence" through a load() statement.
Matt's approach is a better one over the long term.
[Addition: code with Matt's suggested changes]
[Code modified to reflect the fact p is in the .mat file after all]
[Code modified: Minv -> M_inv]
function lambda = drive_zr17t9
format short e;
Params = load('saved_data.mat');
theta = pi/2;
zeta = cos(theta);
I = eye(Params.n,Params.n);
Q = zeta*I-Params.p*Params.p';
%T is a matrix(5,5)
Mroot = Params.M.^(1/2); %optimization

T = Mroot*Q*Mroot;
%find the eigen values
E = eig(T);
%find the negative eigen values -- this section still needs to be fixed
ind = find(E<0);
G = E(ind);
%find the smallest negative eigen value
gamma = min(abs(G)); %this is almost certainly wrong!
%now solve for lambda
bounds = sort([0, -1/gamma]); %in case gamma is positive
M_inv = inv(Params.M); %optimization
lambda = fzero(@(lambda) zr17t9(lambda, M_inv, Q, Params.zm), bounds); %do the searching
end
function r = zr17t9(lambda, M_inv, Q, zm)
Winv = inv(M_inv+lambda.*Q);
r = -zm'*M_inv*Winv*Q*Winv*M_inv*zm;
end
Related Question