How to find number of arrays in a structure filed ?
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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) ?
0 Commenti
Risposta accettata
Siddharth Shankar
il 4 Feb 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);
0 Commenti
Più risposte (2)
Fangjun Jiang
il 4 Feb 2011
>> sum(~cellfun(@isempty,{Av.f1}))
ans =
4
>> sum(~cellfun(@isempty,{Av.f2}))
ans =
2
3 Commenti
Jan
il 4 Feb 2011
With Matt's addition this method is the most efficient solution.
Please, Jiang, insert Matt's addition.
Fangjun Jiang
il 7 Feb 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.
Sandy Patel
il 4 Feb 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
0 Commenti
Vedere anche
Categorie
Scopri di più su Structures in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!