Write Cell arrays to excel file using XlWRITE function ?

3 views (last 30 days)
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');

Accepted Answer

Jan
Jan on 31 Mar 2017
Edited: Jan on 31 Mar 2017
"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');

More Answers (1)

KSSV
KSSV on 31 Mar 2017
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');
  1 Comment
ahmed obaid
ahmed obaid on 31 Mar 2017
thanks a lot , if its possible to accept 2 answers i also accept ,,, thanks again

Sign in to comment.

Categories

Find more on Environment and Settings in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!