在 3D 矩阵中使用 reshape 求平均值
using reshape for a mean in a 3D matrix
我有一个 3D (x,y,nframes) 矩阵/电影(名为 ch)和一个逻辑掩码 (x,y)。我想对每一帧中的蒙版像素求平均值,最后我得到一个暗淡的 1xnframes 向量。我想用重塑而不是逐帧来做,但两个结果不匹配,我不明白为什么......你能告诉我为什么吗???
for i=1:nframes
ch_aux=ch(:,:,i);
Mean_for(i)= mean(ch_aux(mask));
end
% C with reshape
[row,col] = find(mask);
A=ch(row,col,:);
B=reshape(A,1,length(row).^2,nframes );
Mean_res=mean(B);
plot( Mean_for,'r')
hold on
plot( Mean_res(:))
legend({'for','reshape'})
谢谢!
解决方案:
使用reshape
r = reshape( ch, [], size(ch,3) );
Mean_res = mean( r(mask(:),: ), 2 );
基准测试(将此解决方案与 ) can be found here 提出的两个解决方案进行比较显示:
Shai
Elapsed time is 0.0234721 seconds.
Divakar 1
Elapsed time is 0.743586 seconds.
Divakar 2
Elapsed time is 0.025841 seconds.
bsxfun
明显变慢,
原代码中是什么原因导致的错误?
我怀疑你的问题出在表达式 A=ch(row, col,:);
:
假设 ch
的大小为 2×2×n
和 mask = [ 1 0; 0 1];
,在这种情况下
[rox, col] = find(mask);
结果
row = [1,2];
col = [1,2];
而且,很明显,A=ch(row,col,:);
结果 A
正好等于 ch
,这 不是 你想要的...
为了提高效率,您可以使用另一个矢量化解决方案 bsxfun
以及您最喜欢的 reshape
-
Mean_bsxfun = sum(reshape(bsxfun(@times,ch,mask),[],size(ch,3)),1)./sum(mask(:))
或者更好的是,滥用 fast matrix multiplication in MATLAB
-
Mean_matmult = mask(:).'*reshape(ch,[],size(ch,3))./sum(mask(:))
我有一个 3D (x,y,nframes) 矩阵/电影(名为 ch)和一个逻辑掩码 (x,y)。我想对每一帧中的蒙版像素求平均值,最后我得到一个暗淡的 1xnframes 向量。我想用重塑而不是逐帧来做,但两个结果不匹配,我不明白为什么......你能告诉我为什么吗???
for i=1:nframes
ch_aux=ch(:,:,i);
Mean_for(i)= mean(ch_aux(mask));
end
% C with reshape
[row,col] = find(mask);
A=ch(row,col,:);
B=reshape(A,1,length(row).^2,nframes );
Mean_res=mean(B);
plot( Mean_for,'r')
hold on
plot( Mean_res(:))
legend({'for','reshape'})
谢谢!
解决方案:
使用reshape
r = reshape( ch, [], size(ch,3) );
Mean_res = mean( r(mask(:),: ), 2 );
基准测试(将此解决方案与
Shai
Elapsed time is 0.0234721 seconds.
Divakar 1
Elapsed time is 0.743586 seconds.
Divakar 2
Elapsed time is 0.025841 seconds.
bsxfun
明显变慢,
原代码中是什么原因导致的错误?
我怀疑你的问题出在表达式 A=ch(row, col,:);
:
假设 ch
的大小为 2×2×n
和 mask = [ 1 0; 0 1];
,在这种情况下
[rox, col] = find(mask);
结果
row = [1,2];
col = [1,2];
而且,很明显,A=ch(row,col,:);
结果 A
正好等于 ch
,这 不是 你想要的...
为了提高效率,您可以使用另一个矢量化解决方案 bsxfun
以及您最喜欢的 reshape
-
Mean_bsxfun = sum(reshape(bsxfun(@times,ch,mask),[],size(ch,3)),1)./sum(mask(:))
或者更好的是,滥用 fast matrix multiplication in MATLAB
-
Mean_matmult = mask(:).'*reshape(ch,[],size(ch,3))./sum(mask(:))