How to make a for loop for fzero solved functions?

3 visualizaciones (últimos 30 días)
Dameon Solestro
Dameon Solestro el 9 de Dic. de 2021
Comentada: Walter Roberson el 12 de Sept. de 2024
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 comentario
Walter Roberson
Walter Roberson el 12 de Sept. de 2024
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.

Iniciar sesión para comentar.

Respuestas (1)

Rahul
Rahul el 12 de Sept. de 2024
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!

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by