Frage

I want to solve two nonlinear equations in MATLAB so i did the following:

part of my script

c=[A\u;A\v];
% parts of code are omitted.
x0=[1;1];
sol= fsolve(@myfunc,x0);

the myfunc function is as follows

function F = myfunc(x)

  F=[ x(1)*c(1)+x(2)*c(2)+x(1)*x(2)*c(3)+c(4)-ii;

     x(1)*c(5)+x(2)*c(6)+x(1)*x(2)*c(7)+c(8)-jj];

end

i have two unknowns x(1) and x(2)

my question is How to pass a values(c,ii,jj) to myfunc in every time i call it?

or how to overcome this error Undefined function or method 'c' for input arguments of type 'double'.

thanks

War es hilfreich?

Lösung

Edit: The previous answer was bogus and not contributing at all. Hence has been deleted. Here is the right way.

In your main code create a vector of the coefficients c,ii,jj and a dummy function handle f_d

coeffs = [c,ii,jj];
f_d = @(x0) myfunc(x0,coeffs);      % f_d considers x0 as variables
sol = fsolve(f_d,x0);

Make your function myfunc capable of taking in 2 variables, x0 and coeffs

function F = myfunc(x, coeffs)
c = coeffs(1:end-2);
ii = coeffs(end-1);
jj = coeffs(end);

F(1) = x(1)*c(1)+x(2)*c(2)+x(1)*x(2)*c(3)+c(4)-ii;
F(2) = x(1)*c(5)+x(2)*c(6)+x(1)*x(2)*c(7)+c(8)-jj;

I think that should solve for x0(1) and x0(2).

Edit: Thank you Eitan_T. Changes have been made above.

Andere Tipps

There is an alternative option, that I prefer, if a function handle is not what you are looking for.

Say I have this function:

function y = i_have_a_root( x, a )
    y = a*x^2;
end

You can pass in your initial guess for x and a value for a by just calling fsolve like so:

a = 5;
x0 = 0;
root = fsolve('i_have_a_root',x0,[],a);

Note: The [] is reserved for fsolve options, which you probably want to use. See the second call to fsolve in the documentation here for information on the options argument.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top