Arrays of structures indexing
조회 수: 2 (최근 30일)
이전 댓글 표시
Sorry for posting. Google is not helping (me) this time. I have a huge array of structures in the spirit of:
a(1).b=[1 2;3 4];
a(1).c=[10 20;30 40]
a(2).b=[5 6;7 8];
a(2).c=[50 60; 70 80]
(to contextualize: b and c are "some properties" of element 1)
Problem: I need to find "3" (in this case a(1).b(2,1) and get (separately):
- [4] ( which is a(1).b(2,2) )
- [30 40] (which is a(1).c(2,:) )
Solution attempt:
I was thinking to use "find" as:
ind=arrayfun(@(x)find(x.b==3),a,'uniformoutput',false)
ind =
[2.00] [0x1 double]
Now my problem is: how do I use these indices to return [4] and [30 40] ?
Thanks a lot for any input!
댓글 수: 1
Oleg Komarov
2012년 5월 28일
Can elaborate on the logic why a(1).b(2,1) leads to pick a(1).b(2,2) and a(1).c(2,:)?
답변 (1개)
Geoff
2012년 5월 28일
Start by working out which structures had a result:
bValid = ~cellfun( @isempty, ind );
Now, you need to find the row in b. Since you can't get a row/column output from find in an anonymous function, you should either make a subfunction that does this:
[row,~] = find(...)
Or, simply mod the result by the number of rows in your array:
row = cellfun( @(x) mod(x,2), ind(bValid) );
I still don't know the logic for b... Do you choose the second column? Or do you choose the number next to 3? In this case it doesn't matter. I'll choose the second column:
validIdx = find(bValid);
N = numel(validIdx);
bb = nan(N,1);
cc = cell(N,1);
for n = 1:N
idx = validIdx(n);
bb(n) = a(idx).b(rows(n), 2);
cc(n) = a(idx).c(rows(n), :);
end
Something like that, anyway =)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!