Can I dynamically change a structure name

7 ビュー (過去 30 日間)
TastyPastry
TastyPastry 2016 年 5 月 26 日
編集済み: Stephen23 2016 年 5 月 27 日
I have a function which takes in multiple .mat files, reads part of them and consolidates them into a cell array.
Currently my code looks like this:
myData = cell(numel(files),numel(headers)); %preallocate
for i=1:numel(files) %loop through the total number of files
currPath = [filepath files{i}]; %get the current file path
load(currPath);
myData(i,:) = (varName).database(headers) %grab the data
end
In this code, headers are indices of the columns I need data from. The issue lies in the myData(i,:) = ... line where I need to dynamically change (varName). I originally had it hard coded in because I thought the .mat files had consistent file names for the structure array I'm trying to read from, but it turns out that each folder has a different variable name consistent with the name of the folder.
I tried:
%find what the variable name is
varName = strtok(folderName,'_');
But the issue I'm running into is that (varName) doesn't work to substitute in a variable name the same way it works when substituting for a field name when accessing a structure. While I'm able to find the correct imported variable name and store it as a string, it doesn't let me use it as a variable.
I've also tried:
eval(sprintf('%s', varName));
But it just turns out I have no idea how to use eval().
Is there any workaround? I hope I don't have to use a list of try/catch statements...
  1 件のコメント
Stephen23
Stephen23 2016 年 5 月 27 日
編集済み: Stephen23 2016 年 5 月 27 日
Adam's answer is the correct (and best) solution.
Here is why using eval would have been the wrong solution:

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

採用された回答

Adam
Adam 2016 年 5 月 26 日
Use the version of load with an output argument - i.e.
loadedStruct = load( currPath );
Then you will get the contents of your file as fields of a struct and you can use dynamic strings for the field name then:
myData(i,:) = loadedStruct.(varName).database(headers)
  1 件のコメント
TastyPastry
TastyPastry 2016 年 5 月 26 日
Oh wow didn't even think about that. Thanks!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by