How to find number of arrays in a structure filed ?

조회 수: 3 (최근 30일)
Raviteja
Raviteja 2011년 2월 4일
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
Siddharth Shankar 2011년 2월 4일
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