How to make a for loop for fzero solved functions?

Im having some issues making a loop for fzero functions. Basically I want a code that solves for x(i+1) and then uses that value to solve for the next equation
function y=fncsys(x)
x(1)=0.3
y=0
for i=1:4
y = 5(x(i)-x(i+1)) +10((x+i)^2)
end
fzero(@fncsys, 1)

댓글 수: 1

y = 5(x(i)-x(i+1)) +10((x+i)^2)
First of all: that code is inside a for loop, and that code overwrites all of y each iteration. The end result of the loop would have a y corresponding to the highest loop iteration, as if only for i=4 had been executed.
Secondly: the above code requests that the constant 5 be indexed by the floating point value of the expression x(i)-x(i+1) . MATLAB does not allow constants to be indexed by anything. MATLAB has absolutely no implied multiplication: something of the form A(B) is always either function evaluation or indexing.
Thirdly: at the first iteration of the loop, x(1) has been initialized, but you attempt to evaluate x(i+1) where i = 1, so you attempt to evaluate x(2) . That will fail because x(2) has not been set to anything.

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

답변 (1개)

Rahul
Rahul 2024년 9월 12일
I understand that you wish to obtain a code that solves for 'x(i+1)' during each iteration and then similarly uses that value to solve for the next one.
You can use 'current' and 'next' variables in your code to solve the loop iteratively along with using 'fzero' function handle in the loop.
Here is an example:
% Preallocate array 'x'
x = zeros(1, 4);
x(1) = 0.3;
for i = 1:4
% Function handle for 'fzero', passing 'current' and 'next' value of 'x'
fncsys = @(x_next) 5 * (x_current - x_next) + 10 * ((x_current + i)^2);|
% Updating the 'next' value of 'x'
x_next = fzero(fncsys, x_current);
% Updating the 'i+1'th and 'current' value of 'x'
x(i+1) = x_next;
x_current = x_next;
end
% I have used 'x_next' and 'x_current' variables to update the
% 'next' and 'current' values of 'x' respectively.
This code allows updating the 'x(i+1)' values iteratively using the for loop as desired.
You can refer to the following Mathworks documentationz to know more about these functions:
Hope this helps!

카테고리

도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

릴리스

R2021b

질문:

2021년 12월 9일

댓글:

2024년 9월 12일

Community Treasure Hunt

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

Start Hunting!

Translated by