How to find number of arrays in a structure filed ?

3 visualizaciones (últimos 30 días)
Raviteja
Raviteja el 4 de Feb. de 2011
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) ?

Respuesta aceptada

Siddharth Shankar
Siddharth Shankar el 4 de Feb. de 2011
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);

Más respuestas (2)

Fangjun Jiang
Fangjun Jiang el 4 de Feb. de 2011
>> sum(~cellfun(@isempty,{Av.f1}))
ans =
4
>> sum(~cellfun(@isempty,{Av.f2}))
ans =
2
  3 comentarios
Jan
Jan el 4 de Feb. de 2011
With Matt's addition this method is the most efficient solution.
Please, Jiang, insert Matt's addition.
Fangjun Jiang
Fangjun Jiang el 7 de Feb. de 2011
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.

Iniciar sesión para comentar.


Sandy Patel
Sandy Patel el 4 de Feb. de 2011
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

Categorías

Más información sobre Structures en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by