Easy and fast way to export into excel file from loop

조회 수: 2 (최근 30일)
CCF2017 MIT
CCF2017 MIT 2020년 9월 10일
편집: CCF2017 MIT 2020년 9월 10일
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개)

카테고리

Help CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by