필터 지우기
필터 지우기

fzero in a for loop to solve for two variables

조회 수: 19 (최근 30일)
Oisín Conway
Oisín Conway 2022년 10월 9일
편집: Oisín Conway 2022년 10월 9일
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{:});

채택된 답변

Walter Roberson
Walter Roberson 2022년 10월 9일
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
Oisín Conway
Oisín Conway 2022년 10월 9일
편집: Oisín Conway 2022년 10월 9일
Thank you @Walter Roberson for your response and explaining why this is the case.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Optimization에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by