필터 지우기
필터 지우기

How do structures work?

조회 수: 1 (최근 30일)
Chiara Modenese
Chiara Modenese 2011년 4월 13일
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

답변 (2개)

Jarrod Rivituso
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
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
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
  댓글 수: 1
Chiara Modenese
Chiara Modenese 2011년 4월 13일
Well, this is not what I would exactly define as a satisfactory answer. However, I can see there are many workarounds (thanks to Jarrod, too).
Chiara

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

카테고리

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