How do structures work?
1 view (last 30 days)
Show older comments
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 Comments
Answers (2)
Jarrod Rivituso
on 13 Apr 2011
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 Comment
Jarrod Rivituso
on 13 Apr 2011
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
on 13 Apr 2011
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
See Also
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!