Clear Filters
Clear Filters

fzero in a for loop to solve for two variables

20 views (last 30 days)
Hello, i have the following code below and i want two vector for A(1) and A(2) for each iteration of X using fzero in a for loop. Would anyone know how to solve this?
B = 5;
AC = @(A,x) B - 2*A(1) - 5*A(2)*x;
X = 0:1:10;
N = numel(X);
Z = nan(0,N);
for k = 1:N
Z(k) = fzero(@(A)AC(A,X(k)),[0 0])
end
Error using fzero>localFirstFcnEval
FZERO cannot continue because user-supplied function_handle ==> @(A)AC(A,X(k)) failed with the error below.

Index exceeds the number of array elements. Index must not exceed 1.

Error in fzero (line 245)
fa = localFirstFcnEval(FunFcn,FunFcnIn,a,varargin{:});

Accepted Answer

Walter Roberson
Walter Roberson on 9 Oct 2022
AC = @(A,x) B - 2*A(1) - 5*A(2)*x;
That requires that A is a vector or array with two or more elements.
Z(k) = fzero(@(A)AC(A,X(k)),[0 0])
fzero will generate scalar values and pass them one by one as parameters to the anonymous function, and the anonymous function will pass the scalars as the first parameter to the anonymous function named AC. But AC needs the first parameter to be a vector.
You want fzero() to pass a vector of two elements to the anonymous function. It looks like you are hoping that the initial value of the vector would be [0, 0]
However... fzero() is strictly a solver for a single variable. You can never use fzero to solve for two variables simultaneously. Although fzero() accepts the vector of two values [0, 0] as the initial condition, what that means to fzero() is that the lower bound of the search range is to be 0 (first element of [0, 0]) and the upper bound of the search range is to be 0 (second element of [0,0])
I suggest you look at bit more closely at your equation:
B - 2*A(1) - 5*A(2)*x == 0
B - 2*A(1) == 5*A(2)*x
(B - 2*A(1))/x = 5*A(2) %assuing nonzero x
A(2) = (B - 2*A(1))/x %assuming nonzero x
And that means that for any given non-zero x value, you can select any finite A(1) value, and there will be a finite A(2) that solves the equation.
Therefore it is not possible to solve for A(1) and A(2) simultaneously, except in the sense of getting some indeterminate combination of A(1) and A(2) the depends upon the starting point and the details of the search algorithm.
There is thus no point in doing this search. If you want to use fixed A(1) or A(2) you can calculate the other of the two algebraically without using any root finder.
  1 Comment
Oisín Conway
Oisín Conway on 9 Oct 2022
Edited: Oisín Conway on 9 Oct 2022
Thank you @Walter Roberson for your response and explaining why this is the case.

Sign in to comment.

More Answers (0)

Categories

Find more on Optimization in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!