Is there a way to find if a variable exists inside a MAT file?

79 ビュー (過去 30 日間)
MathWorks Support Team
MathWorks Support Team 2016 年 3 月 3 日
編集済み: MathWorks Support Team 2017 年 1 月 16 日
Is there a way to find if a variable exists inside a MAT file? I have saved several MAT files and in a different script I want to find out if those MAT files have a certain variable in them and if they do I want to load them.

採用された回答

MathWorks Support Team
MathWorks Support Team 2017 年 1 月 16 日
This can be done by specifying additional arguments to the "load" command. MATLAB will search for each additional string argument as a variable name within the MAT files specified in the first argument. If it does not find a variable of that name, it will throw a warning. If it does find one, it will load the variable. Here is a simple example to read all the MAT files in a given directory and load a variable named 'myVar' if it exists.
myFiles = dir('*.mat');
for i=1:length(myFiles)
    clear myVar;
    load(myFiles(i).name,'myVar')
    if exist('myVar','var')
        disp(['myVar = ' num2str(myVar)]); %display the value of myVar
    else
        %do something if it doesn't load.
    end
end
In order to achieve this without using the 'load' command, use the 'who' function with '-file' argument.
https://www.mathworks.com/help/matlab/ref/who.html
 
variableInfo = who('-file', 'census.mat');
ismember('pop', variableInfo) % returns true
ismember('doesNotExist', variableInfo) % returns false
  1 件のコメント
Steven Lord
Steven Lord 2016 年 12 月 15 日
Use the who function with the -file input argument.
variableInfo = who('-file', 'census.mat');
ismember('pop', listOfVariables) % returns true
ismember('doesNotExist', listOfVariables) % returns false
If you need to check not only for variables names but also other qualities of the variable, use the whos function instead. Note that whos returns a struct array, not simply a list of names.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeWorkspace Variables and MAT Files についてさらに検索

製品


リリース

R2015b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by