Solving a System of Nonlinear Equations n Times With Different Values

4 visualizaciones (últimos 30 días)
Hi, I am trying to solve a system of nonlinear equations n times, and recording the output values for each time. For simplicity I wrote less complex, random nonlinear equations here rather than what I was working with, but it is the same idea. I have tried a number of things, and this skeleton of code has been the closest, but I cannot get it to return different values for each iteration. I found that I cannot embed a function into a large for loop because of MATLAB syntax, and placing the for loop within the function returns nothing. I believe that fsolve only solves the system of equations for z1(10) and z2(10) and not the first 9 values in the vectors. I can't find any information on how to change this. Any help would be greatly appreciated.
x0 = [1,1];
m = 10; % same length as z1 below, because I want to output 10 values
c = 0; % counting value
for q=1:m
x = fsolve(@g,x0)
c = c+1;
p(:,c) = x; % records each output value
end
function F = g(x)
z1 = [5 6 7 8 9 10 11 12 13 14];
z2 = [1 2 3 4 5 6 7 8 9 10];
n = length(z1)
for i=1:n
F(1) = x(1).*x(2) - z1(i)
F(2) = x(1) + x(2)./x(1) - z2(i)
end
end

Respuesta aceptada

Sam Chak
Sam Chak el 5 de Mayo de 2024
Editada: Sam Chak el 5 de Mayo de 2024
When fsolve calls the system function g(x), it consistently executes the same number of loops until n reaches 10, and then returns the final solution for the system of double nonlinear equations. You can fix the code as follows:
x0 = [1, 1]; % static initial guess
c = 0; % initialize counting parameter
z1 = [5 6 7 8 9 10 11 12 13 14];
z2 = [1 2 3 4 5 6 7 8 9 10];
opt = optimoptions('fsolve','Display', 'none'); % can also choose 'iter'
%% call fsolve
for q = 1:numel(z1)
x = fsolve(@(x) g(x, z1(q), z2(q)), x0, opt);
c = c + 1;
p(:,c) = x; % records each output value
end
%% display results
disp(p)
2.0817 2.2543 2.3982 3.2361 4.5688 5.6913 6.7592 7.8029 8.8334 9.8559 2.1666 2.5410 2.8756 2.4721 1.9699 1.7571 1.6274 1.5379 1.4717 1.4205
%% system of double nonlinear equations
function F = g(x, z1, z2)
F(1) = x(1).*x(2) - z1;
F(2) = x(1) + x(2)./x(1) - z2;
end

Más respuestas (0)

Categorías

Más información sobre Systems of Nonlinear Equations en Help Center y File Exchange.

Productos


Versión

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by