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!