フィルターのクリア

How do I call a struct name from variables stored in a cell array in a loop?

23 ビュー (過去 30 日間)
Fizzle
Fizzle 2018 年 9 月 15 日
コメント済み: Marcelo Moraes 2021 年 12 月 30 日
Greetings all:
So I have three structs named method1, method2, and method3. I also have a cell array (named structNames) that contains the name of the structs. The problem is that I get an error (that reads "Struct contents reference from a non-struct array object") when I try to extract the content of the structs in a for loop. Is there a way around this: Here is a sample code:
structNames = {method1,method2,method3};
method1.mean = 3;
method2.mean = 4;
method3.mean = 5;
meanSum = 0;
for m = 1:length(structNames)
meanExtract = structNames{m}.mean;
meanSum = meanSum + meanExtract;
end
  1 件のコメント
jonas
jonas 2018 年 9 月 15 日
編集済み: jonas 2018 年 9 月 15 日
You should never name variables nor structs dynamically. As a rule of thumb, never store meta data as part of the variable name if you intend to access it via a loop. What you can do is to name fields dynamically. You could for example store method1-3 in one struct (let's call it data), and access its via dynamic field names:
f1={'m1','m2','m3'}
for i=1:3
data.(f1{i}).mean
end

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

採用された回答

Image Analyst
Image Analyst 2018 年 9 月 15 日
I don't think people would really recommend that approach, but here is one way to solve it using the hated eval() function:
method1.mean = 30;
method2.mean = 40;
method3.mean = 50;
method4.mean = 60;
method5.mean = 70; % Whatever....
structNames = {'method1','method2','method3'}; % List of structs we want to use now.
thisSum = 0;
for m = 1:length(structNames)
commandString = sprintf('%s.mean', structNames{m})
thisMean = eval(commandString)
thisSum = thisSum + thisMean
end
meanSum = thisSum / length(structNames)

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by