Write Cell arrays to excel file using XlWRITE function ?
1 次查看(过去 30 天)
显示 更早的评论
Dear all, i would like to print a sequence of string data to a certain excel file, by i can not print based on the following code: and why data-name is repeated 5 times in command window ? thanks
n = 5;
for i = 1:n
data-name{i} = {sprintf('day%s',num2str(i))}
end
% Write out the cell array all in one shot and write day1...dayn
xlswrite('D:\name.xls', data-name, 'Sheet1', 'A1');
0 个评论
采纳的回答
Jan
2017-3-31
编辑:Jan
2017-3-31
"data-name" is not a valid name for a Matlab variable. Names for functions and variables cannot contain a minus. How sould Matlab distinguish the variable "a-b" form the subtraction of "b" from "a" otehrwise?
When a command is not closed by a semicolon, Matlab prints the result to the command window. You wrote: "data-name is repeated 5 times in command window", but as long as "data-name" is not a valid Matlab name, this cannot happen, but an error message must occur. Did you post the original code? If not: please do not do this. The simplifications frequently shadow the actual error.
sprintf is perfect for converting numbers to strings. You do not need to call num2str in addition.
In
dataname{i} = {sprintf('...')}
you have created a cell vector containing cell strings. xlswrite requires a cell string, such that there is one level of curly braces too much.
Pre-allocation is essential. For 5 strings this will not be measurable. But it is a good programming practice to write code such that it will be usable even if n is set to 50'000.
For using "i" as loop counter see Answers: i and j as variable names. This is not an error, but can cause unexpected effects.
n = 5;
dataname = cell(1, n); % Pre-allocate!
for k = 1:n
dataname{k} = sprintf('day%d', k);
end
xlswrite('D:\name.xls', dataname, 'Sheet1', 'A1');
更多回答(1 个)
KSSV
2017-3-31
n = 5;
for i = 1:n
data_name{i} = sprintf('day%s',num2str(i)) ;
end
% Write out the cell array all in one shot and write day1...dayn
xlswrite('D:\name.xls', data_name, 'Sheet1', 'A1');
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Spreadsheets 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!