How to find number of arrays in a structure filed ?

3 次查看(过去 30 天)
Hello all,
Av(1).f1=[1 2 3 4]; Av(2).f1=[3 4 5 6]; Av(3).f1=[5 3 2 1]; Av(4).f1=[7 8 2 4];
Av(1).f2=[1 2 3 4 5]; Av(2).f2=[7 6 5 4 3];
I created a structure Av with two fields f1,f2.
I need to konw N1=number of arrays in Av.f1... N2=number of arrays in Av.f2...
So I tried
>> N=size(Av)
N =
1 4
>> N1=size(Av.f1)
??? Error using ==> size
Too many input arguments.
>> N2=size(Av.f2) ??? Error using ==> size Too many input arguments.
I have to get N1=4, N2=2
Please tell me how to calculate (N1 and N2) ?

采纳的回答

Siddharth Shankar
Off the top of my head:
function [N1, N2] = fieldCount(inputStruct)
N1 = 0;
N2 = 0;
for i = 1: numel(inputStruct)
if(~isempty(getfield(inputStruct(i),'f1')))
N1 = N1 + 1;
end
if(~isempty(getfield(inputStruct(i),'f2')))
N2 = N2 + 1;
end
end
You can call this function as follows:
[N1, N2] = fieldCount(Av);

更多回答(2 个)

Fangjun Jiang
Fangjun Jiang 2011-2-4
>> sum(~cellfun(@isempty,{Av.f1}))
ans =
4
>> sum(~cellfun(@isempty,{Av.f2}))
ans =
2
  3 个评论
Jan
Jan 2011-2-4
With Matt's addition this method is the most efficient solution.
Please, Jiang, insert Matt's addition.
Fangjun Jiang
Fangjun Jiang 2011-2-7
Thanks for the tip! cellfun('isempty',...) is much faster than cellfun(@isempty,...) on a large cell array. Where should I get this info? Is it documented? According to the help of cellfun(), function handle is the recommended syntax. The use of strings for a few of those functions is accepted for backward compatibility.

请先登录,再进行评论。


Sandy Patel
Sandy Patel 2011-2-4
This might be a little confusion on the matlab's data structure.
You could have just as easily made an structure with the following data:
Av(1).f1=[1 2 3 4]; Av(2).f1=[3 4 5 6]; Av(3).f1=[5 3 2 1]; Av(4).f1=[7 8 2 4 999];
Notice the last value made Av(4).f1 one element larger.
In this case
>> size(Av(1).f1,2)
ans =
4
>> size(Av(4).f1,2)
ans =
5
So it asking for the size of Av.f1 would not give a unique answer. If you know ahead of time that the size of all the f1 vectors will be the same, then you can just do
size(Av(1).f1,2)
size(Av(1).f2,2)
to get the sizes that you need.
Hope this helps.
Cheers, Sandy

类别

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