下面是简单代码:
A=zeros(60,60,30);
a=rand(28,28,30);
for i=1:30
m=round(rand*32)+1; %because 60-28=32
n=round(rand*32)+1;
A(m:m+27,n:n+27,i)=a(:,:,i);
end
它所做的就是简单地取一个28*28的随机矩阵并将其"植入"到一个更大的(零)矩阵中,并重复30次。每次,它随机选择一个不同的角位置(即'm'和'n')将小矩阵放入大矩阵中。我确信我可以做到这一点没有for
循环-只是不确定如何。
这里所有的技巧都是关于MATLAB中使用的线性索引。我们创建偏移线性索引,并牢记最终输出的大小。首先,要创建偏移索引,以便索引到A
的一个3D切片,然后索引到整个3D数组。在代码中分别命名为offset2D
和offset3D
。最后,我们将m
和n
的线性索引相加。
假设您将m
和n
索引保存到两个单独的1D数组中,例如m_arr
和n_arr
,那么您将拥有bsxfun
的最终矢量化实现,如下所示-
%// Say you have the m,n arrays are created like this -
m_arr = round(rand(30,1)*32)+1;
n_arr = round(rand(30,1)*32)+1;
%// Get linear indices with m,n
mn_arr = (n_arr-1)*size(A,1) + m_arr;
%// Calculate offset indices for 2D and then 3D versions
offset2D = bsxfun(@plus,[0:27]',[0:27]*size(A,1)); %//'
offset3D = bsxfun(@plus,offset2D(:),[0:30-1]*numel(A(:,:,1)));
%// Incorporate m,n indices into offset to get final linear indices to index into A
lidx = bsxfun(@plus,mn_arr(:).',offset3D); %//'
%// Initialize output array and then index into A to values from a
A = zeros(60,60,30);
A(lidx) = a;
为方便将来的读者,这里有For循环和矢量化代码的参数化版本——
%// Parameters
M = 4;
D = 3;
mx = 3;
%// For-loop code
A = zeros(M+mx,M+mx,D);
a = rand(M,M,D);
m_arr = round(rand(D,1)*mx)+1;
n_arr = round(rand(D,1)*mx)+1;
for i=1:D
m = m_arr(i);
n = n_arr(i);
A(m:m+M-1,n:n+M-1,i) = a(:,:,i);
end
%// Vectorized code
mn_arr = (n_arr-1)*size(A,1) + m_arr;
offset2D = bsxfun(@plus,[0:M-1]',[0:M-1]*size(A,1)); %//'
offset3D = bsxfun(@plus,offset2D(:),[0:D-1]*numel(A(:,:,1)));
lidx = bsxfun(@plus,mn_arr(:).',offset3D); %//'
A_vectorized = zeros(M+mx,M+mx,D);
A_vectorized(lidx) = a;
最后,让我们比较循环码和向量化码的输出-
>> max(abs(A(:)-A_vectorized(:)))
ans =
0