Creating table with all iterations of function

3 views (last 30 days)
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:')
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'})
T = 1×3 table
Root Value Function Value Relative Error __________ ______________ ______________ 0.90625 -0.034092 3.4483

Answers (1)

Amey Waghmare
Amey Waghmare on 20 Oct 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.

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!