Search code examples
matlabwaitexists

Wait while variable does not exist MATLAB


I need to suspend the program until the variable is created. I point to the data file, then open uiimport to specify the range of data. And at this moment I have to suspend the program until the variable is created.

%find file
[FileName,PathName] = uigetfile({'*.xls;*.xlsx', 'Excel files(*.xls, *.xlsx)'},'Укажите Excel-файл с данными');
%open import wizard
uiimport(strcat(PathName, FileName));
% here i need to suspend the program until the variable is created

Solution

  • You must specify an output variable when calling uiimport. If you do this, no lines after your call to uiimport will be executed until uiimport has completed (the user has chosen data to import or not).

    data = uiimport(fullfile(PathName, FileName));
    
    % Do stuff with data
    disp(data.value)
    

    If for some reason, you did need to wait until a variable existed, you could use a while loop combined with exist, but in general this is a marker of poor program design.

    while ~exist('variablename', 'var')
        % Do something that may define the variable
    end
    

    Update

    If you're simply reading an excel file, it is likely easier to use xlsread to do so:

    data = xlsread(filename, -1);