Creating table with all iterations of function
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
I am trying to run this code and get it to show each of the iterations for the function up until itmax = 4. Any idea how I can get it to print separate iterations in the same table using the code I have as of now?
es = 1E-6; % Stopping criterion (%).
itmax = 4; % Maximum number of iterations.
xl = 0.5; % Initial lower bound of the interval.
xu = 1; % Initial upper bound of the interval.
xr = 0.8; % Initial approximation of the root.
fx = @(x) sin(x) - (x.^2); % Function of interest.
for it = 1:itmax
xrold = xr;
xr =(xl+xu)/2; % Approximation of the root.
if (xr~=0)
ea = abs((xr-xrold)/xr)*100; % Approximate relative error.
end
test = fx(xl)*fx(xr); % Half-interval test.
if (test<0)
xu=xr;
elseif (test>0)
xl=xr;
else
ea = 0;
end
if (ea<=es), break, end
end
disp('Bisection method results:')
root = xr; % Estimated root via the Bisection method when converge
func = fx(xr); % Function value at the estimated root
ea; % Relative error
T = table(root', func', ea', 'VariableNames', {'Root Value', 'Function Value', 'Relative Error'})
0 Kommentare
Antworten (1)
Amey Waghmare
am 20 Okt. 2022
Hi,
As per my understanding, you are trying to display the values of variables root, func and ea in the Table T for each iteration.
In order to store the values for each variable, you can initialize an empty array for each variable at the beginning of the code using:
xr_arr = zeros(1, itmax);
where the index of the array corresponds to the iteration number, and then update values at each index in the for loop using:
xr_arr(it) = xr;
At the end when you are creating the table, you can pass xr_arr instead of xr to the table function. Similar workflow can be done for other variables in your code.
I hope this resolves the issue.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!