# Im trying to import my result data into excel but i will only create one iteration can someone please help

1 view (last 30 days)
Fernando Piedra on 14 Sep 2020
Answered: Mazhar Mohammed on 15 Sep 2020
In line 65 i try to create a peice of code that exports to excel dont work the way i want it. im also attaching the files thanks in advance
function [sq_root] = sqroot(num)
format long
converge = false;
iter = 0;
%Max allow of error
esp = 10^-10;
%intial guess
xn=1;
%disp('iter, x_n, err_est; err_exact');
tru_err_arr = [];
est_err_arr = [];
iter_arr = [];
%Using imporove initial value to find sqrt
if num >= 1
xn =1;
while xn^2<num
xn = xn+10;
end
xn = xn/2;
else
xn =1;
while xn^2>num
xn = xn/10;
end
xn = xn*2;
end
while converge == false
%Function definations
f = xn^2-num;
df = 2*xn;
%newton_raphson
nr = xn -(f/df);
%error defination
tru_err = sqrt(num)-xn;
est_err = nr-xn;
tru_err_arr =[tru_err_arr, tru_err];
est_err_arr =[est_err_arr, est_err];
%error check
if abs(est_err/xn)<esp
converge = true;
end
disp([iter, xn,est_err, tru_err]);
%Iteration counter
iter_arr = [iter_arr, iter];
iter = (iter+1);
xn=[];
xn=nr;
%----attemp to export to excel------------
R0 = {'iter','xn', 'est_err', 'tru_err'};
R1 = iter_arr;
R2 = xn;
R3 = est_err_arr;
R4 = tru_err_arr;
xlswrite('results.xlsx', R0,'Sheet1','A1');
xlswrite('results.xlsx', R1,'Sheet1','A2');
xlswrite('results.xlsx', R2,'Sheet1','B2');
xlswrite('results.xlsx', R3,'Sheet1','C2');
%-----------------------------------------------
end
sq_root = xn;
disp('Determining the square root of:');
disp(num);
disp(['The sqrt of ', num2str(num),' is: ' ]);
disp(sq_root);
disp('Number of iteration taken:');
disp(iter-1);
info_plot(tru_err_arr, est_err_arr, iter_arr);
end

Mazhar Mohammed on 15 Sep 2020
Hi
In line number 71-74 cell values are getting overwritten in every iteration of while loop. To avoid this, create an array matrix before while loop
arr = ['iter','xn', 'est_err', 'tru_err'];
Inside the loop you can append the values to the existing array. For example:
row = {iter_arr,xn, est_err_arr, tru_err_arr};
arr = [arr; row];
Then write it into excel after loop gets completed.
writecell(arr,'results.xlsx','Sheet',1);

R2017b

### Community Treasure Hunt

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

Start Hunting!