How to import multiple files in matlab, using uige

2019-08-05 05:20发布

问题:

I want to select multiple files, import the data from the files and use them in GUI program.
The code I am using to get the multiple files works perectly well:

[FileName,PathName,FilterIndex] = uigetfile('*.txt*','Study Files','MultiSelect','on')

Cols = size(FileName,2);
numfiles = Cols;


for i = 1:numfiles
    FileName(i)

    entirefile =fullfile(PathName,FileName(i))
end   

My problem is when I try to open entire file. The method I'm trying to use works with a single file but not here.When the code in the loop is:

for i = 1:numfiles
    FileName(i)

    entirefile =fullfile(PathName,FileName(i))

 A = [];
 fid = fopen(entirefile);

 tline = fgets(fid);
 while ischar(tline)
     parts = textscan(tline, '%f;');
     if numel(parts{1}) > 0
         A = [ A ; parts{:}' ];
      end
     tline = fgets(fid);

 end  
end  

Error using fopen First input must be a file name of type char, or a file identifier of type double.

Error in multiselect (line 14) fid = fopen(entirefile);

It also only gives me the first and last file selected and then only the entirefile of the first selected file.

Anyone any suggestions on how I could resolve this issue?

回答1:

The issue is how you access the element of the cell array FileName. If you access it with regular brackets, the output will be a one-element cell array, and fullfile will therefore output a cell array as well. You need to access it with curly brackets like this FileName{i}.

This should work:

[FileName,PathName,FilterIndex] = uigetfile('*.txt*','MultiSelect','on');

numfiles = size(FileName,2);

for ii = 1:numfiles
    FileName{ii}

    entirefile =fullfile(PathName,FileName{ii})

    fid = fopen(entirefile);
    % your code

    fclose(fid);

end