求优化 关于矩阵赋值
有个有意思的优化问题,矩阵b是行索引,a是列索引;c是要放的值;按照索引 b 和 a,把值c放在矩阵ss中b =;
a =;
c =;
ss=NaN(2,2);
结果应该是ss=【33 44;11 22】
求助如何高效实现?
b =;
a =;
c =;
ss=NaN(2,2);
linearInd =sub2ind(size(ss), b, a)
ss(linearInd)=>> ss(linearInd)=
ss =
33 44
11 22 liuyalong008 发表于 2013-7-2 21:30 static/image/common/back.gif
en 果然要比我的厉害。。谢谢
ps:我的笨办法:
bb=reshape(b,1,numel(b));
aa=reshape(a,1,numel(a));
index=(aa-1)*size(ss,1)+bb;
ss(index) = c;
几种实现方法:
1. sub2ind,楼上liu版已经解释过了。也是我个人比较推荐的方法。
2. arrayfun+reshape, 如 reshape(arrayfun(@(x) c(b(x), a(x)), 1:numel(c)), size(c))
3. 用subsasgn构造,相对最麻烦。ss = nan(size(c));
subsasgn(ss,struct('type','()','subs',{{1:numel(c)}}),arrayfun(@(x) c(b(x), a(x)), 1:numel(c))); 给定位置给定元素可以用稀疏矩阵来构造ss = full(sparse(b,a,c))也可以用accumarray来做accumarray(,c(:)) 厉害厉害厉害厉害厉害
页:
[1]