讨论和代码
这可能是一种方法bsxfun(@plus http://in.mathworks.com/help/matlab/ref/bsxfun.html这有利于linear indexing http://in.mathworks.com/help/matlab/math/matrix-indexing.html以函数格式编码 -
function out = bsxfun_linidx(A,a)
%// Get sizes
[A_nrows,A_ncols] = size(A);
N_a = numel(a);
%// Linear indexing offsets between 2 columns in a block & between 2 blocks
off1 = A_nrows*N_a;
off2 = off1*A_ncols+A_nrows;
%// Get the matrix multiplication results
vals = bsxfun(@times,A,permute(a,[1 3 2])); %// OR vals = A(:)*a_arr;
%// Get linear indices for the first block
block1_idx = bsxfun(@plus,[1:A_nrows]',[0:A_ncols-1]*off1); %//'
%// Initialize output array base on fast pre-allocation inspired by -
%// http://undocumentedmatlab.com/blog/preallocation-performance
out(A_nrows*N_a,A_ncols*N_a) = 0;
%// Get linear indices for all blocks and place vals in out indexed by them
out(bsxfun(@plus,block1_idx(:),(0:N_a-1)*off2)) = vals;
return;
如何使用:要使用上面列出的函数代码,假设您有a1
, a2
, a3
, ...., an
存储在向量中a
,然后做这样的事情out = bsxfun_linidx(A,a)
以获得所需的输出out
.
标杆管理
本节将此答案中列出的方法与其他答案中列出的其他两种方法进行比较或基准测试,以了解运行时性能。
其他答案被转换为函数形式,就像这样 -
function B = bsxfun_blkdiag(A,a)
B = bsxfun(@times, A, reshape(a,1,1,[])); %// step 1: compute products as a 3D array
B = mat2cell(B,size(A,1),size(A,2),ones(1,numel(a))); %// step 2: convert to cell array
B = blkdiag(B{:}); %// step 3: call blkdiag with comma-separated list from cell array
and,
function out = kron_diag(A,a_arr)
out = kron(diag(a_arr),A);
为了进行比较,四种尺寸组合A
and a
进行了测试,它们是 -
-
A
as 500 x 500
and a
as 1 x 10
-
A
as 200 x 200
and a
as 1 x 50
-
A
as 100 x 100
and a
as 1 x 100
-
A
as 50 x 50
and a
as 1 x 200
接下来列出了使用的基准测试代码 -
%// Datasizes
N_a = [10 50 100 200];
N_A = [500 200 100 50];
timeall = zeros(3,numel(N_a)); %// Array to store runtimes
for iter = 1:numel(N_a)
%// Create random inputs
a = randi(9,1,N_a(iter));
A = rand(N_A(iter),N_A(iter));
%// Time the approaches
func1 = @() kron_diag(A,a);
timeall(1,iter) = timeit(func1); clear func1
func2 = @() bsxfun_blkdiag(A,a);
timeall(2,iter) = timeit(func2); clear func2
func3 = @() bsxfun_linidx(A,a);
timeall(3,iter) = timeit(func3); clear func3
end
%// Plot runtimes against size of A
figure,hold on,grid on
plot(N_A,timeall(1,:),'-ro'),
plot(N_A,timeall(2,:),'-kx'),
plot(N_A,timeall(3,:),'-b+'),
legend('KRON + DIAG','BSXFUN + BLKDIAG','BSXFUN + LINEAR INDEXING'),
xlabel('Datasize (Size of A) ->'),ylabel('Runtimes (sec)'),title('Runtime Plot')
%// Plot runtimes against size of a
figure,hold on,grid on
plot(N_a,timeall(1,:),'-ro'),
plot(N_a,timeall(2,:),'-kx'),
plot(N_a,timeall(3,:),'-b+'),
legend('KRON + DIAG','BSXFUN + BLKDIAG','BSXFUN + LINEAR INDEXING'),
xlabel('Datasize (Size of a) ->'),ylabel('Runtimes (sec)'),title('Runtime Plot')
我最终获得的运行时图是 -
结论:如您所见,任一bsxfun
可以研究基于方法,具体取决于您正在处理的数据类型!