How to append data into an Excel File when writing data in a loop.?
21 次查看(过去 30 天)
显示 更早的评论
I am writing an complex double 10X1 variable X into an excel file inside a loop. The value of X updates for every iteration of the loop. But the data keeps getting over written. The values inside the complex double X are being to every row in a particular column of the excel sheet. See below for the code.
for i = 1:44
% code to calculate the value of X
R(1,1:length(X))=X;
xlswrite(write_file,R');
end
So for column A of the excel sheet, in the row 1 to 10 (A1 to A10) the data within X gets written in the first loop. Then during the 2nd time it gets re-written on top of the old data and so on.
0 个评论
回答(1 个)
Madheswaran
2024-11-13,11:47
Hi
The 'xlswrite' function is not recommended starting from MATLAB R2019a. To write a column vector into an Excel file, you can use the 'writematrix' function.
If you want to append all the values in a single column, you can use the 'WriteMode' parameter set to 'append':
for i = 1:44
% existing code to calculate the value of X
writematrix(X, filename, 'WriteMode', 'append');
end
However, if you would like to append each of the column vectors in separate columns, you can modify your loop as follows:
function colName = getColumnName(colNumber)
colName = "";
while colNumber > 0
modulo = mod(colNumber - 1, 26);
colName = char('A' + modulo) + colName;
colNumber = floor((colNumber - modulo) / 26);
end
end
for i = 1:44
% existing code to calculate the value of X
colName = getColumnName(i);
writematrix(X, filename, 'Range', sprintf('%s1', colName));
end
The above function 'getColumnName' converts integer to Excel Column name. For more information on 'writetable', refer to the following documentation: https://mathworks.com/help/matlab/ref/writetable.html
Hope this helps!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Spreadsheets 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!