1

I am working on a small project which requires huge amount of data to be imported into matlab for further processing. I have currently 15 excel files and each file has 8 sheets. What I want is to make a parent structure in which I want load each excel file as a structure e.g.

parentstructure.filename.value{} 

Where parentstructure is a main structure and filename is an excel file which is an another structure in parent structure and each excel file has a 8 sheets in a cell.

I have written a small code to read data into matlab. The code is as follows

srcdir = '';  %%% where all the files are placed
srcfiles = dir(fullfile(srcdir, '*.xls'));

for p = 1:numel(srcfiles)

    filename = fullfile(srcdir, srcfiles(p).name);
    [~,sheets] = xlsfinfo(srcfiles(p).name);

    for i = 1:8
        Sheet = char(sheets(1,i)) ;
        value{p,i} = xlsread(filename,Sheet);

    end
end

This code works fine and loads the data into matlab but not in the structrue form I wanted. I tried several other combinations and adjustments but getting errors. Any help or guuide will be much appreciated. Thank you

Suever
  • 64,497
  • 14
  • 82
  • 101
Muhammad
  • 67
  • 1
  • 1
  • 7

1 Answers1

2

In the code that you've postsed, you haven't actually created the struct. You do this using the struct keyword. Then, in order to assign each file to a filename field, you'll want to use genvarname (or matlab.lang.makeValidName) to convert the filename to a valid field name and assign the struct to this.

% Initialize Parent Structure
parentStructure = struct();

srcdir = '';  %%% where all the files are placed
srcfiles = dir(fullfile(srcdir, '*.xls'));

% Sort the files by numbers in their names
numbers = regexp({srcfiles.name}, '\d+', 'match');
numbers = str2double(cat(1, numbers{:}));
[~, sortind] = sort(numbers);
srcfiles = srcfiles(sortind);

for p = 1:numel(srcfiles)

    % Convert filename to a valid field name
    fieldname = matlab.lab.makeValidName(srcfiles(p).name);

    filename = fullfile(srcdir, srcfiles(p).name);
    [~,sheets] = xlsfinfo(filename);

    value = cell(1,8);

    for k = 1:8
        Sheet = char(sheets(1,k)) ;
        value{k} = xlsread(filename,Sheet);
    end

    % Now assign this struct of sheets to your parentStructure
    parentStructure.(fieldname) = value;
end
Suever
  • 64,497
  • 14
  • 82
  • 101
  • it worked and data is loaded.But now the problem is files are not loaded in sequence. This is because the file names starts as a numeric number e.g. 1.xls,2.xls and so on. But in a structure matlab is arranging is way like 1.xls,10.xls,11.xls... 2.xls,3.xls..... Is there any way to make matlab to read files in sequence and dont adjust them?. This is important as rest of my code depends on this. – Muhammad Jun 11 '16 at 14:34
  • @Muhammad I have added the sorting part to the code above – Suever Jun 11 '16 at 15:01