Operations in structure with N fields named sequencially.

2 ビュー (過去 30 日間)
Jose Rego Terol
Jose Rego Terol 2020 年 5 月 31 日
コメント済み: Stephen23 2020 年 5 月 31 日
Hi,
I created this structure (S) with 26 fields named sequencially. Each field has only one column and N number of rows (e.g. S.myfield1 (65x1), S.myfield2 (70x1), and so on). I just want to get the mean of S (all the fields).
mean_S=mean(S)
Error using sum
Invalid data type. First argument must be numeric or logical.
Error in mean (line 127)
y = sum(x, dim, flag) ./ mysize(x,dim);
So I transformed the structure into cell (struc2cell). I can get the mean of each cell (e.g. each field in the structure) but I cannot get the mean of two cells:
B=struct2cell(S);
mean_B1=mean(B{1,1});
mean_B1_26=mean(B{:,1});
Error using mean
Too many input arguments.
Also, I am interested in getting the min , max and std of S.
I could not find any page with this info regarding structure operations. Any solution?
Update*
I am looking that my structure is different as normal structure.
I load a -mat file containing 26 variables as
S=load('myfile.mat')
So, my structure is 1x1 with 26 fields. The Field is the name of each variable and the value of each field is the number of rows X number of columns (1)
  2 件のコメント
Jose Rego Terol
Jose Rego Terol 2020 年 5 月 31 日
cell2mat(struct2cell(S));
Still I am looking for other solution for operating structures
Stephen23
Stephen23 2020 年 5 月 31 日
"I created this structure (S) with 26 fields named sequencially."
It would be simpler and more efficient to use a non-scalar structure:

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

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 5 月 31 日
Try this
y = mean(structfun(@mean, s));
  2 件のコメント
Jose Rego Terol
Jose Rego Terol 2020 年 5 月 31 日
It works! thanks. also for the rest. May you explain me in-depth this code? I have seen several times but I cannot understand the meaning of the first mean and the second mean. The second mean calls the function mean, right? Therefore I don not get the purpose of the first mean.
Ameer Hamza
Ameer Hamza 2020 年 5 月 31 日
The mean() in
structfun(@mean, s)
call the mean() function on each field of the struct 's'. It will output an array. The outside mean() than take the mean of the returned array.
While writing this comment, I realized that using mean() like this will not give the correct answer. Following is the correct method
sum_s = sum(structfun(@sum, s));
num_s = sum(structfun(@numel, s));
avg = sum_s/num_s;

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by