Search code examples
arraysmatlabcell

Non-cell array with uigetfile in Matlab


My code has 2 parts. First part is an automatic file opening programmed like this :

fichierref = 'H:\MATLAB\Archive_08112012';
files = dir(fullfile(fichierref, '*.txt'));
numberOfFiles = numel(files);
delimiterIn = ' ';
headerlinesIn = 11;
for d = 1:numberOfFiles
    filenames(d) = cellstr(files(d).name);
end

for i=1:numberOfFiles
    data = importdata(fullfile(fichierref,filenames{i}),delimiterIn,headerlinesIn);
end

Later on, I want the user to select his files for analysis. There's a problem with this though. I typed the lines as follow :

reference = warndlg('Choose the files from which you want to know the magnetic field');
uiwait(reference);
filenames = uigetfile('./*.txt','MultiSelect', 'on');
numberOfFiles = numel(filenames);
delimiterIn = ' ';
headerlinesIn = 11;

It's giving me the following error, after I press OK on the prompt:

Cell contents reference from a non-cell array object.

Error in FreqVSChampB_no_spec (line 149)
data=importdata(filenames{1},delimiterIn,headerlinesIn);

I didn't get the chance to select any text document. Anyone has an idea why it's doing that?


Solution

  • uigetfile is a bit of an annoying when used with `MultiSelect': when you select multiple files the output is returned as a cell array (of strings). However, when only one file is selected the output is of type string (not a cell array with a single cell, as one would have expected).

    So, in order to fix this:

    filenames = uigetfile('./*.txt','MultiSelect', 'on');
    if ~iscell(filenames) && ischar( a )
        filenames = {filenames}; % force it to be a cell array of strings
    end
    % continue your code here treating filenames as cell array of strings.
    

    EDIT:
    As pointed out by @Sam one MUST verify that the user did not press 'cancel' on the UI (by checking that filenames is a string).