gpt4 book ai didi

matlab - 对二维矩阵中的 block 求和 - MATLAB

转载 作者:太空宇宙 更新时间:2023-11-03 19:18:03 24 4
gpt4 key购买 nike

我正在研究 Matlab,想知道如何在大型矩阵中添加项。具体来说,我有一个 4914x4914 矩阵并想创建一个 189x189 矩阵,其中每个项等于每个 26x26 中项的总和> 子集。

为了说明,假设我有如下神奇的 4x4 矩阵:

[16 2  3  13;

5 11 10 8;

9 7 6 12;

4 14 15 1]

我想创建一个 2x2 矩阵等于原始魔术 4x4 中每个 2x2 矩阵的总和,即:

[(16+2+5+11)   (3+13+10+8);

(9+7+4+14) (6+12+15+1)]

感谢任何建议!谢谢 jack

最佳答案

假设 A 是输入 4914x4914 矩阵,这可能是一种有效的(就运行时而言)方法 -

sublen = 26; %// subset length
squeeze(sum(reshape(sum(reshape(A,sublen,[])),size(A,1)/sublen,sublen,[]),2))

对于通用 block 大小,我们有一个函数 -

function out = sum_blocks(A,block_nrows, block_ncols)
out = squeeze(sum(reshape(sum(reshape(A,block_nrows,[])),...
size(A,1)/block_nrows,block_ncols,[]),2));
return

sample 运行-

>> A = randi(9,4,6);
>> A
A =
8 2 4 9 4 5
3 3 8 3 6 8
9 6 6 7 1 9
4 5 5 7 1 2
>> sum_blocks(A,2,3)
ans =
28 35
35 27
>> sum(sum(A(1:2,1:3)))
ans =
28
>> sum(sum(A(1:2,4:6)))
ans =
35
>> sum(sum(A(3:4,1:3)))
ans =
35
>> sum(sum(A(3:4,4:6)))
ans =
27

如果您想避免挤压 -

sum(permute(reshape(sum(reshape(A,sublen,[])),size(A,1)/sublen,sublen,[]),[1 3 2]),3)

基准测试

希望您关心性能,这里是此处发布的所有解决方案的基准测试结果。我用过的基准测试代码-

num_runs = 100; %// Number of iterations to run benchmarks
A = rand(4914);
for k = 1:50000
tic(); elapsed = toc(); %// Warm up tic/toc
end

disp('---------------------- With squeeze + reshape + sum')
tic
for iter = 1:num_runs
sublen = 26; %// subset length
out1 = squeeze(sum(reshape(sum(reshape(A,sublen,[])),...
size(A,1)/sublen,sublen,[]),2));
end
time1 = toc;
disp(['Avg. elapsed time = ' num2str(time1/num_runs) ' sec(s)']), clear out1 sublen

disp('---------------------- With kron + matrix multiplication')
tic
for iter = 1:num_runs
n = 189; k = 26;
B = kron(speye(k), ones(1,n));
result = B*A*B';
end
time2 = toc;
disp(['Avg. elapsed time = ' num2str(time2/num_runs) ' sec(s)']),clear result n k B

disp('---------------------- With accumarray')
tic
for iter = 1:num_runs
s = 26; n = size(A,1)/s;
subs = kron(reshape(1:(n^2), n, n),ones(s));
out2 = reshape(accumarray(subs(:), A(:)), n, n);
end
time2 = toc;
disp(['Avg. elapsed time = ' num2str(time2/num_runs) ' sec(s)']),clear s n subs out2

我在系统上获得的基准测试结果 -

---------------------- With squeeze + reshape + sum
Avg. elapsed time = 0.050729 sec(s)
---------------------- With kron + matrix multiplication
Avg. elapsed time = 0.068293 sec(s)
---------------------- With accumarray
Avg. elapsed time = 0.64745 sec(s)

关于matlab - 对二维矩阵中的 block 求和 - MATLAB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26280418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com