How to address the fields of a struct with function input arguments
古いコメントを表示
Hallo
i have a function with input arguments like
function FUNC(x,y)
and trying to work with struct fields within the function. I can load it with:
load(['Struct_Nr' num2str(x)]);
but i cant adress the fields using x, y
ans = mean(['Struct_Nr' num2str(x) 'Field_Nr' num2str(y)]) %does not work for example
I need char to variable or something like that.
1 件のコメント
Stephen23
2017 年 4 月 13 日
This is a bad way to write code, and should be avoided:
採用された回答
その他の回答 (2 件)
Geoff Hayes
2015 年 1 月 17 日
Immelmann - to be clear, you have a number of structs that have been saved to individual files named (for example), Struct_Nr1.mt, Struct_Nr2.mat, etc., and each file has a single structure of the same name? What are the field names? Are they individually numbered like Field_Nr1, Field_Nr2, etc.?
I guess the problem that you are experiencing is that when you load the file as
load(['Struct_Nr' num2str(x)]);
you now have a local variable whose name is Struct_Nr1 (for example), with no real way to access it or its fields without referring back to the x. If you can't format all of your struct data in to some sort of matrix or cell array (and so avoid all the multiple files), then you could try the following
function FUNC(x,y)
% create a structure that will have the single variable loaded from file
myStruct = load(['Struct_Nr' num2str(x)]);
% get the fields of this structure (and there will just be one, that which
% corresponds to the structure loaded from file)
varNameCellArray = fields(myStruct);
% so you know the variable name, and you wish to access a particular field
% from it to calculate the mean
avg = mean(myStruct.(char(varNameCellArray)).(['Field_Nr' num2str(y)]));
% etc.
Note how we use char to wrap varNameCellArray to convert the single element cell array to a string. We then access the Field_Nr in a similar manner.
Try the above and see what happens!
Immelmann
2015 年 1 月 17 日
カテゴリ
ヘルプ センター および File Exchange で Scope Variables and Generate Names についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!