How to pass in a list of variables to "load" function without using eval?

12 ビュー (過去 30 日間)
K E
K E 2014 年 5 月 19 日
コメント済み: K E 2014 年 5 月 19 日
Is there a way to load in a list of variables from a file, if the list of variables is passed in? I would like to avoid using eval. Here is what I am doing:
% Create dummy variables so this example works
dog = rand(1,5); cat = rand(1,5);
budgie = rand(1,5); fish = rand(1,5);
alligator=rand(1,5); hamster = rand(1,5);
% Create dummy file
save('myPetsFile.mat'); % Real mat file is large, 50+ variables
petList = {'dog', 'cat', 'budgie'};
filePets = 'myPetsFile.mat';
strPets = sprintf('''%s'',', petList{:}); % Add single quotes and comma
strPets = strPets(1:end-1); % Remove trailing comma
eval(['PS = load(filePets, ' strPets ');']);
I also would like to be able to combine the listed variables with additional directly-named variables, such as 'fish', 'alligator' in this example, but again avoid the eval command:
eval(['PS = load(filePets, ' strPets ', ''fish'', ''alligator'');']);

採用された回答

Kelly Kearney
Kelly Kearney 2014 年 5 月 19 日
Don't need the sprintf at all, as long as petList is already a cell array of strings:
PS = load(filePets, petList{:});
  1 件のコメント
K E
K E 2014 年 5 月 19 日
Perfect, thanks. Knew there had to be a simpler way! This works too,
PS = load(filePets, petList{:}, 'fish', 'alligator');

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

その他の回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 5 月 19 日
PS = load(filePets, sprintf('%s',petList{:}))
  1 件のコメント
K E
K E 2014 年 5 月 19 日
The load command seems to want the quotes and commas in its inputs which is why I had to use eval. I revised the example.

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

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by