MATLAB Answers


Setting name of variable equal to name of imported file

Asked by John
on 19 Dec 2011


I'm importing data into Matlab from excel via the following command:


How can I set the name of the metadata to be the same as the name of the imported excel file.For example: = 'DC';

It will be looping through files in a folder so I wont know the name in advance

Many thanks



No products are associated with this question.

2 Answers

Answer by Robert Cumming
on 19 Dec 2011

if you must do it then use dynamic fieldnames

   metadata.( = cycle


on 19 Dec 2011

Thanks for the reply,

Maybe I didn't describe it very well, I want to save it with the same as the imported excel file, not as the variable cycle.

Would you suggest the same in this case?

Many thanks

Full code:

nrows = size(cycle,1);
sch_key_on=[0 1; nrows 1]; = 'DC';
save DC.mat

Robert Cumming
on 19 Dec 2011

same theory. TO get the filename use:

[fullpath, filename, ext] = fileparts ( 'E:\DC.xlsx' );

Then: = filename;

on 19 Dec 2011

Thanks very much

Answer by Matt Tearle
on 19 Dec 2011

If you're going to be looping on the files, you're probably doing something like

x = cellstr(ls('*.xlsx'));
for k = 1:length(x)
  % do stuff

In the "do stuff" bit, you should use fileparts to pull apart each filename string:

[~,fn] = fileparts(x{k}); = fn;
% or save([fn,'.mat']) if you want to be explicit

  1 Comment

on 19 Dec 2011

Thanks very much

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi test

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!