# how to sum value of fields on struct?

190 visualizzazioni (ultimi 30 giorni)
fred bnm il 26 Ott 2016
Risposto: Karol Ondrejkovic il 28 Mar 2023
i have a struct in size 1000*1 with 2 fields.how to sum value of fields? my code:(s is struct)
sum1 = sum(s.Fields1(1:end));
##### 2 CommentiMostra NessunoNascondi Nessuno
KSSV il 26 Ott 2016
Did that work? You got any error?
fred bnm il 27 Ott 2016
no but i cant obtain sum of values in the fields.

Accedi per commentare.

### Risposte (4)

KSSV il 26 Ott 2016
s = struct ;
for i = 1:100
s(i).a = rand(1) ;
s(i).b = i ;
end
suma = sum([s(:).a]) ;
sumb = sum([s(:).b]) ;
##### 1 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
khuat quanghuy il 19 Set 2018
thanks.

Accedi per commentare.

Andrei Bobrov il 26 Ott 2016
Modificato: Andrei Bobrov il 26 Ott 2016
z = struct2cell(s(:));
out = sum(reshape([z{:}],size(z)),2);
or general variant
z = cellfun(@(x)x(:)',struct2cell(s(:)),'un',0);
out = arrayfun(@(ii)sum([z{ii,:}]),(1:size(z,1))');
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

sourav malla il 4 Lug 2019
You can do it with a for loop like this:
sum1=0;
for i=1:length(s)
sum1=sum1+s(i).fieldname
end
or you can directly do like this:-
sum1=sum([s(:).fieldname])
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Karol Ondrejkovic il 28 Mar 2023
s = struct; % create a scalar (1-by-1) structure with no fields
N = 1000; % number of fields to be created
for i = 1 : N
s(i).a = i + 1; % s(1).a = 2; s(2).a = 3; s(3).a = 4; ... ; s(N).a = 1001; (fill "a" fields with scalar values)
s(i).b = i; % s(1).b = 1; s(2).b = 2; s(3).b = 3; ... ; s(N).b = 1000; (fill "b" fields with scalar values)
end
% Sumation of scalar values:
c = struct2cell(s); % convert (1 by N) struct to (2 by 1 by N) cell array
ca_sum = sum([c{1,1,:}], 2); % sum of the elements in the "a" fields
cb_sum = sum([c{2,1,:}], 2); % sum of the elements in the "b" fields
c_sum = sum([c{:}]); % sum of the elements in the "a+b" fields
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### 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!

Translated by