Indirect addressing in structure

조회 수: 5 (최근 30일)
developer
developer 2011년 9월 8일
Hello, I have structure P that has 20 fileds now if i have to adrress the values indirectly like
x =
4
5
6
9
and i have to addrress 4th ,5th,6th and 9th of values of structure P, how can i do that
Thanks in advance

답변 (3개)

Jan
Jan 2011년 9월 8일
You can use STRUCT2CELL to convert the struct to a cell at first:
S = struct('Field1', 1, 'Field2', 2, 'Field3', 3);
C = struct2cell(S);
disp(C{1});
disp(C{3});
% A partial list of values:
x = [1, 3];
D = C(x);
  댓글 수: 2
Andrei Bobrov
Andrei Bobrov 2011년 9월 8일
Hi Jan! Another way
fld = fields(P)
D = cellfun(@(x)P.(x),fld(x),'un',0);
Jan
Jan 2011년 9월 8일
@Andrei: Is FIELDS documented now? Otherwise I'd suggest the older and documented FIELDNAMES.

댓글을 달려면 로그인하십시오.


Harry MacDowel
Harry MacDowel 2011년 9월 8일
It works like this:-
P.variable = rand(20,1);
x = [4 5 6 9];
for ii=1:4
P.variable(x(ii)) = ii;
end
  댓글 수: 2
Harry MacDowel
Harry MacDowel 2011년 9월 8일
ah maybe I misunderstood your question. =)
Andrei Bobrov
Andrei Bobrov 2011년 9월 8일
this question the continuation of this question <http://www.mathworks.com/matlabcentral/answers/15309-variable>

댓글을 달려면 로그인하십시오.


Wesley Ooms
Wesley Ooms 2011년 9월 8일
If i understand correct, it can be done with the command
'fieldnames' it returns the names of the fields in a cell array.
p.a=1
p.b=2
p.c=3
name=fieldnames(p)
p.(name{1})

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by