How do structures work?
조회 수: 1 (최근 30일)
이전 댓글 표시
Hi there. Say that I use an array of structures and that then I want to create an array like:
[ss.phi] % ss is the array of structures, and phi a number
Now, the above works just fine but what does not work is:
[ss.phi(1)] % this time phi is an array of doubles and I only want to keep the first element
Why is the last case wrong? And how to fix it?
Thanks. Chiara
댓글 수: 0
답변 (2개)
Jarrod Rivituso
2011년 4월 13일
I think MATLAB doesn't let you nest subscripts like that. However, there are workarounds. Is this what you are looking for:
>> var(1).a = [3 4];
>> var(2).a = [5 6];
>> var(1).b = 10;
>> var(2).b = 13;
>> getFirstElementFcn = @(x) x(1);
>> allFieldsA = {var.a};
>> cellfun(getFirstElementFcn, allFieldsA)
댓글 수: 1
Jarrod Rivituso
2011년 4월 13일
Note that I've created an anonymous function to go through and grab the first element, and then I've put all the field values in a structure array, and then finally I apply the function to the field values within the cell.
Oleg Komarov
2011년 4월 13일
ss.phi = rand(10);
ss.phi = ss.phi(1)
Saying it's not working is as far as you can get from a clear description of a problem.
EDIT Following Jarrod's interpretation (which by the way, I now think, is your situation), another way:
var(1).a = [1 2; 3 4];
var(2).a = [5 6; 7 8];
temp = cat(3,var.a);
squeeze(temp(1,1,:))
Or fetching elements in a loop (no vectorized way available):
% Preallocate
...
for s = 1:numel(var)
out(...) = var(s).a(1)
end
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!