Extracting variables from a struct array with many empty structs

I have a giant struct array and many of which are empty.
struct array with fields: f1, f2, f3. i.e. Struct Array: StAr(i,j) has StAr(i,j).f1, StAr(i,j).f2,StAr(i,j).f3. But I want to create a new Array by just collecting all the f1 values without using a for loop.
(1) Since many of the structs in the array are empty when I do [StrAr.f1] it gives me a row vector from the non-empty structs. How do I substitute the empty struct values with 0 instead of a matrix.
or
(2) Just get the index of non-empty structs?
Thanks guys

回答 (1 件)

Andrei Bobrov
Andrei Bobrov 2012 年 10 月 23 日
編集済み: Andrei Bobrov 2012 年 10 月 24 日

0 投票

k = {StAr.f1};
out = zeros(size(k));
nonempty = ~cellfun(@isempty,k);
out(nonempty) = [StAr.f1]; % (1)
idx = find(nonempty); % (2)
EDIT
k = {StAr.f1};
k1 = cellfun(@(x)x(:).',k,'un',0);
ii = cellfun(@isempty,k1);
k1(ii) = {0};
out = cell2mat(k1); % (1)
idx = find(ii); % (2)
EDIT 2
k = reshape({StAr.f1},size(StAr));
k2 = cellfun(@(x)x(:).',k,'un',0);
ii = cellfun(@isempty,k2);
k2(ii) = {nan};
s2 = cellfun('size',k2,2);
out = cell2mat(cellfun(@(x,y)[x,nan(1,y - numel(x))],...
k2,num2cell(ones(size(s2,1),1)*max(s2)),'un',0));

4 件のコメント

Sam Da
Sam Da 2012 年 10 月 23 日
I forgot to mention that f1, f2, f3 can are vectors of varying length for various (i,j). i.e. for some (i,j) f1 can be 1x3 and for another (i,j) it can be 1x25.
How should I modify the above code?
Thanks
Andrei Bobrov
Andrei Bobrov 2012 年 10 月 23 日
see EDIT
Sam Da
Sam Da 2012 年 10 月 23 日
In this step: k = {StAr.f1};
the original array structure is flattened out to be a row vector. Can I preserve the array structure and keep it m x n. I am not great with Matlab so please excuse my silly questions.
Andrei Bobrov
Andrei Bobrov 2012 年 10 月 24 日
see EDIT 2

サインインしてコメントする。

カテゴリ

タグ

質問済み:

2012 年 10 月 23 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by