how to write data from a loop to excel file

1 回表示 (過去 30 日間)
alex kariuki
alex kariuki 2015 年 7 月 7 日
編集済み: bio lim 2015 年 7 月 8 日
Io=0.86;
Iv=0.43;
for theta= 0:6:360
Imax = Io+Iv+2*cos (theta)*sqrt(Io.*Iv);
Imin = Io+Iv-2*cos (theta)*sqrt(Io.*Iv);
fringe_contrast =(Imax-Imin)/(Imax+Imin);
end
how do i store the values of theta, Imax, Imin and fringe_contrast in an excel file to show all the values generated from the loop?

回答 (1 件)

bio lim
bio lim 2015 年 7 月 7 日
編集済み: Stephen23 2015 年 7 月 8 日
Io=0.86;
Iv=0.43;
theta = 0:6:360; % Better use vectorization
Imax = Io+Iv+2*cos(theta) * sqrt(Io.*Iv);
Imin = Io+Iv-2*cos(theta) * sqrt(Io.*Iv);
fringe_contrast = (Imax-Imin)./(Imax+Imin); % Element-wise division
filename = 'data.xlsx';
A = {'theta','Imax','Imin','fringe_contrast'; theta.', Imax.', Imin.', fringe_contrast.'};
sheet = 1;
xlRange = 'B1';
xlswrite(filename, A, sheet, xlRange)
I don't have MATLAB installed for the laptop I am using right now, so I cannot check right now. Tell me if there is any problem.
  3 件のコメント
alex kariuki
alex kariuki 2015 年 7 月 8 日
Thanks alot for your comments
The code you provided only writes headers to the excel file, what i was actually interested in is the for-loop. As you can see, Imax and Imin values change as i perform cos of theta (theta is angles from 0 to 360 insteps of 6 degrees).
I want to write the values of the Imax, Imin, and fringe_contrast in an excel file according to the different values of theta.
That's why i included a for-loop, may be you didn't see the loop in my question.
bio lim
bio lim 2015 年 7 月 8 日
編集済み: bio lim 2015 年 7 月 8 日
Hi Alex. Try Sid's nice corrected version.
Io=0.86;
Iv=0.43;
theta = 0:6:360; % Better use vectorization
Imax = Io+Iv+2*cos(theta) * sqrt(Io.*Iv);
Imin = Io+Iv-2*cos(theta) * sqrt(Io.*Iv);
fringe_contrast =(Imax-Imin)./(Imax+Imin);
tableHeaders = {'theta','Imax','Imin','fringe_contrast' };
filename = 'data.xlsx';
sheet = 1;
xlRange = 'A1';
xlswrite(filename, tableHeaders, sheet, xlRange)
mainArrayToWrite = [theta.', Imax.', Imin.', fringe_contrast.'];
filename = 'data.xlsx';
sheet = 1;
xlRange = 'A2';
xlswrite(filename, mainArrayToWrite, sheet, xlRange)
Using loop is often not ideal, because they take longer than vectorization. Checked it and it works. HTH

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCalendar についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by