问题
I have a 3-by-3-by-3 struct, struct
, with fields bit
. In each field I have two values. I want to divide values of each field by a summation of values of each field in dimension 3
for example if
struct(1,1,1).bit=[2, 3]
struct(1,1,2).bit=[4, 5]
struct(1,1,3).bit=[6, 7]
my new struct values must be for example:
newstruct(1,1,1).bit=[2/(2+4+6) , 3/(3+5+7)]
newstruct(1,1,2).bit=[4/(2+4+6) , 5/(3+5+7)]
newstruct(1,1,3).bit=[6/(2+4+6) , 7/(3+5+7)]
回答1:
As it is MATLAB, you should possibly go with an nD
array instead of the struct
.
Yet, if you still want to do it this way, don't fear the good old for
-loop:
for d1 = 1:size(in,1)
for d2 = 1:size(in,2)
d3sum = sum(cat(1,in(d1,d2,:).bit),1);
for d3 = 1:size(in,3)
out(d1,d2,d3).bit = in(d1,d2,d3).bit./d3sum;
end
end
end
回答2:
I think the only way to do this is with a for
loop, or to use nD arrays:
s(1,1,1).bit = [2 3];
s(1,1,2).bit = [4 5];
s(1,1,3).bit = [6 7];
[m,n,p] = size(s);
[mm,nn] = size(s(1,1,1).bit); % assume all elements of the structure have the same dimension
struct_sum = zeros(1,nn);
% compute the sums
for k=1:p
struct_sum = struct_sum+s(1,1,k).bit;
end
% create the new stucture
for k=1:p
s1(1,1,k).bit = s(1,1,k).bit./struct_sum;
end
UPDATE: option with nD array
s(1,1,1,1:2)=[2 3];
s(1,1,2,1:2)=[4 5];
s(1,1,3,1:2)=[6 7];
s1 = s./sum(s); % you can specify sum(s,3) to sum along the 3rd dimension - you may also need to use squeeze(...) to remove unnecessary dimensions
Check it gives the correct results:
>> s1(1,1,:,1)
ans =
ans(:,:,1) = 0.16667
ans(:,:,2) = 0.33333
ans(:,:,3) = 0.50000
>> [2 4 6]/12
ans =
0.16667 0.33333 0.50000
>> s1(1,1,:,2)
ans =
ans(:,:,1) = 0.20000
ans(:,:,2) = 0.33333
ans(:,:,3) = 0.46667
>> [3 5 7]/15
ans =
0.20000 0.33333 0.46667
来源:https://stackoverflow.com/questions/27961332/summation-values-in-structure-in-matlab