Code covered by the BSD License  

Highlights from
getfilevar

getfilevar

by

 

26 Oct 2011 (Updated )

Allows user to define the name of unknown variable from .mat file and load it into the workspace.

getfilevar(varargin)
function[variable,varargout] = getfilevar(varargin)

% [variable,variablename] = getfilevar(filename,dlg,sel1) RETURNS THE VARIABLE
% SELECTED FROM .mat FILE filename AS A VARIABLE OF THE SAME TYPE BUT WITH A
% NAME SPECIFIED BY THE USER variable.
%
% getfilevar CAN BE CALLED WITH NO INPUTS ALLOWING THE USER TO SPECIFY
% A FILENAME INTERACTIVELY THROUGH A GUI
%
% dlg IS AN OPTIONAL FIELD TO SPECIFY THE PROMPT IN THE LIST DIALOG WINDOW.
%
% variablename IS AN OPRIONAL OUTPUT CONTAINING THE NAME OF THE VARAIBLE
% LOADED FROM THE ORIGINAL FILE. THIS IS HANDY FOR PLOTS AND TABLES, ETC.
%
% sel1 IS A STRING SELECTION FILTER THAT CAN BE USED TO IDENTIFY VARAIBLES IN
% THE FILE WITH MATCHING NAMES.
%
% getfilevar ALLOWS YOU TO GET A VARIABLE WITH AN UNKNOWN NAME AND USE IT
% IN AN EXISTING FUNCTION OR SCRIPT WITHOUT HAVING TO REWRITE THE CODE.
%
% SAM ROBERSON -- TNO, UTRECHT, THE NETHERLANDS - 26.10.2011
if nargin < 1
    [fname,pname,~] = uigetfile;
    filename = sprintf('%s%s',pname,fname);
    dlg = 'select variable';
    nc = 25;
elseif nargin < 2
    filename = varargin{1};
    dlg = 'select variable';
    nc = 25;
elseif nargin < 3
    filename = varargin{1};
    dlg = varargin{2};
    nc = length(dlg)+1;
elseif nargin < 4
    filename = varargin{1};
    dlg = varargin{2};
    nc = length(dlg)+1;
    sel1 = varargin{3};
end

tstr = 'getfilevar';
vars = whos('-file',filename); % this can take a while on large files
[nv,~] = size(vars);
varsStr = cell(nv,1);
for i = 1:nv
    varsStr{i} = vars(i).name;
end
if nargin > 2 % apply string filter
    a = 0;
    for i = 1:nv
        a = a+1;
        b = regexpi(varsStr{a},sel1);
        if isempty(b);
            varsStr(a) = [];
            a = a-1;
        end
    end
    nv = a;
end
h = min(15*nv, 400);
sel2 = listdlg('ListString',varsStr,'PromptString',dlg,'ListSize',[nc*5 h],...
    'Name',tstr,'SelectionMode','Single');
var = load(filename,varsStr{sel2});
variable = var.(varsStr{sel2}); % allocate variable
if nargout > 1
    varargout{1} = varsStr{sel2};
end

Contact us