フィルターのクリア

Accessing/writing a fieldname values for a blind structure

3 ビュー (過去 30 日間)
Rick
Rick 2014 年 3 月 11 日
コメント済み: Rick 2014 年 3 月 11 日
Okay, so lets say you got a function that you want to generically send structures too for writing out. I figured out how to get to the field names and write them out for headers. However, I cannot figure out how to access the actuall values for the structure and they're perspective data type. I am using Matlabe 2010B.
Here is what I got:
function write_datastruct(person) %person = [] %person.name = 'Robbie'; %person.age = 38; %person.height = 58;
%access/write out the fieldnames for a header xfields = fieldnames(person); fieldcnt = length(xfields);
for ii = 1:fieldcnt fprintf('\t%s',xfields{ii}); end
Now how do I access/write the values of person............. ??? This does not work:
for jj = 1:fieldcnt fprintf('\t',person.fields{jj}); end

採用された回答

Patrik Ek
Patrik Ek 2014 年 3 月 11 日
編集済み: Patrik Ek 2014 年 3 月 11 日
You may want something like this,
function printfields(theStruct)
fields = fieldnames(theStruct);
for k = 1:length(fields)
if isstruct(theStruct.(fields{k}))
fprintf('%s\n ',fields{k})
printfields(theStruct.(fields{k}))
else
if k > 1
fprintf(' ');
end
if isa(theStruct.(fields{k}),'char')
fprintf(':%s\n',theStruct.(fields{k}));
else
fprintf(':%g\n',theStruct.(fields{k}));
end
end
end
Try it on
a.b.c = 1;
a.c.d = 'a';
You may also want it to work for cells so then you must do a,
elseif isa(theStruct.(fields{k}),'cell')
printcell(theStruct.(fields{k}));
where you may need to write/find a function printing cells.
  1 件のコメント
Rick
Rick 2014 年 3 月 11 日
THANK YOU too Patrik for your TIME..... Yes Sir thats it.

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

その他の回答 (1 件)

David Sanchez
David Sanchez 2014 年 3 月 11 日
person.name = 'xx';
person.age=32;
xfields = fieldnames(person)
>> person.(xfields{1})
ans =
xx
>> person.(xfields{2})
ans =
32
  2 件のコメント
Rick
Rick 2014 年 3 月 11 日
David, How do I give it a format in a fprintf write statement ??
Patrik Ek
Patrik Ek 2014 年 3 月 11 日
This do not work for more than one layer.

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

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by