Easy and fast way to export into excel file from loop

14 次查看(过去 30 天)
I want to give output from a nested loop to an excel file.
for k = 1:61
%nested loop here
%then the relevent code for output is:
if c == 0&&c1 == 0&&c2 == 0&&c3 == 0&&c4 == 0
E = 0.84;
elseif c == 1&&c1 == 0&&c2 == 0&&c3 == 0&&c4 == 0
E = 0.88;
elseif c == 1&&c1 == 1&&c2 == 0&&c3 == 0&&c4 == 0
E = 0.92;
elseif c == 1&&c1 == 1&&c2 == 1&&c3 == 0&&c4 == 0
E = 0.94;
elseif c == 1&&c1 == 1&&c2 == 1&&c3 == 1&&c4 == 0
E = 0.95;
elseif c == 1&&c1 == 1&&c2 == 1&&c3 == 1&&c4 == 1
E = 0.96;
else
disp('Not Valid')
end
E_cell = sprintf('D%s', num2str(k));
xlswrite(filename , E, 'Sheet1', E_cell)
end
  1 个评论
Johannes Hougaard
Johannes Hougaard 2020-9-10
Do you need to append the data to the same Excel file for each k or do you need to create 61 different excel files?
From your code it seems that you wish to write the value of E in column D of Sheet1 of your excelfile filename. Is that a correct assumption?
And again - I'd assume what happens is that your value for k = 61 is written in cell D61 of your Sheet1 and nothing else is stored in your excel file.

请先登录,再进行评论。

采纳的回答

Johannes Hougaard
Johannes Hougaard 2020-9-10
You should concatenate your E variable before writing the excelfile as xlswrite creates a file rather than edits a file. As an added benefit this will be substantially faster as you only do one call to xlswrite and will allow you to inspect your variable E_out as well.
filename = "thisisanewexcelfile.xlsx";
E_out = nan(61,1);
E_cell = "D1";
for k = 1:61
%nested loop here
%then the relevent code for output is:
if c == 0&&c1 == 0&&c2 == 0&&c3 == 0&&c4 == 0
E = 0.84;
elseif c == 1&&c1 == 0&&c2 == 0&&c3 == 0&&c4 == 0
E = 0.88;
elseif c == 1&&c1 == 1&&c2 == 0&&c3 == 0&&c4 == 0
E = 0.92;
elseif c == 1&&c1 == 1&&c2 == 1&&c3 == 0&&c4 == 0
E = 0.94;
elseif c == 1&&c1 == 1&&c2 == 1&&c3 == 1&&c4 == 0
E = 0.95;
elseif c == 1&&c1 == 1&&c2 == 1&&c3 == 1&&c4 == 1
E = 0.96;
else
disp('Not Valid')
end
E_out(k) = E;
end
xlswrite(filename , E_out, 'Sheet1', E_cell);
  1 个评论
CCF2017 MIT
CCF2017 MIT 2020-9-10
编辑:CCF2017 MIT 2020-9-10
I appreciate your input for a more refined code.
I found the problem to be something else entirely (probably because of realmin and thus irrelevant to this topic). It was resolved by adding 0.00001 (or simply a negligible value>min. possible) to the inequalities.

请先登录,再进行评论。

更多回答(0 个)

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by