How to create a table to show the results of a function code?

11 views (last 30 days)
function s = snlnewt(f,J,X0,eps,itmax)
% f is a vector of anonymous function;
% J is the Jacobian matrix of f;
% X0 is the vector that contains the initial approximation;
% eps is the tolerance choosen;
% itmax is the max iteration allowed to run the code.
%% Nonlinear system %%
% x^2 + y^2 = 1
% x^2 - y = 0
% inicial guess x=1 and y=0.9
%eps = 10^-4
%itmax = 10
% i'm calling this function by snlnewt(@(x) [x(1)^2+x(2)^2-1;x(1)^2-x(2)],@(x) [2*x(1) 2*x(2); 2*x(1) -1],[1; 0.9], 10^-4, 10)
it = 1; % first iteraction
xo = X0; % xo assumes the values of the initial approximation
dx = eliminacao_gauss( J(xo), -f(xo) ) % dx is the solution of the linear sistem J\(-f) whitch is solved by gauss method
xk = xo + dx % giving xk the most recent value on the actual iteration
erro = norm(xk-xo)/max(abs(xk))
%% repeat the process until the error (eps) is reached
while erro >eps
it = it + 1;
xo=xk;
dx = eliminacao_gauss( J(xo), -f(xo) )
xk = xo + dx
if it == itmax %stop the code
break
end
end
p=xk % final solution
disp('Solução do SNL')
disp(p)
disp('Iterações')
disp(it) % disp the total number of iterations
end
How can I create a table to show the data of each iteration like
it | dx | xk | erro ??
Never mind any mistakes in english, I'm not a native.

Accepted Answer

Star Strider
Star Strider on 17 Oct 2021
Subscript the variables so they are column vectors, then put them in the table and return the table as one of the outputs (or perhaps the only output).
while erro >eps
itv(:,it) = it;
xo(:,it)=xk;
dx(:,it) = eliminacao_gauss( J(xo), -f(xo) );
xk(:,it) = xo + dx;
erro(:,it) = norm(xk-xo)/max(abs(xk));
if it == itmax %stop the code
break
end
it = it + 1;
end
s = table(itv,dx,xk,erro);
Note that ‘s’ is not otherwise defined anywhere, so I assigned the table array to it.
.
  2 Comments
Eduardo Fornazieri
Eduardo Fornazieri on 17 Oct 2021
For some reason, there was a error message on the command window saying
" Error using tabular/countVarInputs (line 267)
All variables must have the same number of rows.
Error in table (line 213)
[numVars,numRows] = tabular.countVarInputs(varargin); "
Anyway, I've done some ajustments in your reply and the final code is:
while erro >eps
itv(:) = it;
xo(:)=xk;
dx(:) = eliminacao_gauss( J(xo), -f(xo) );
xk(:) = xo + dx;
erro(:) = norm(xk-xo)/max(abs(xk));
if it == itmax %stop the code
break
end
p(it,:) = table(itv',dx',xk',erro',...
'VariableNames',{'k' 'dx' 'xk' 'erro'});
it = it + 1;
end
s = p;
by now, it's working the way I was expecting. Thank you, bro! I couldn't do it before without your help!

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!