Matlab中结构的求和值 [英] summation values in structure in matlab
本文介绍了Matlab中结构的求和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 3 -by- 3 -by- 3 结构struct
,其字段为bit
.在每个字段中,我都有两个值.我想将每个字段的值除以维度3中每个字段的值之和
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
例如
struct(1,1,1).bit=[2, 3]
struct(1,1,2).bit=[4, 5]
struct(1,1,3).bit=[6, 7]
我的新结构值必须为:
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)]
推荐答案
我认为唯一的方法是使用for
循环或使用nD数组:
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
更新:带有nD阵列的选项
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
这篇关于Matlab中结构的求和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文