我在 MATLAB 中编写了一小段代码。这实际上是一个从 3D 矩阵生成线性索引的函数。这实际上是一个更大项目的一部分。问题是代码有效,但没有优化,而且速度很慢。当我在 MATLAB 上运行分析器时,该函数消耗了 90% 的计算时间。如何优化此代码?
%
A = rand(3,3);
H = 1200;
W = 1500;
S = rand(H,W,3,'uint8')
R = zeros(H,W,3,'uint8');
lIR = zeros(1,H*W*3);
lIC = zeros(1,H*W*3);
count = 0;
for rY = 1:1:H
for rX = 1:1:W
[oX,oY] = func1(rX,rY);
cP = A*[oX; oY; 1];
cP = cP / cP(3);
cX = round(cP(1)); cY = round(cP(2));
if cX < size(S,2) && cX > 1 && cY < size(S,1) && cY > 1
lIR(count+1:count+3) = sub2ind([size(R) 1],[rY rY rY], [rX rX rX],1:3);
lIC(count+1:count+3) = sub2ind([size(S) 1],[cY cY cY],[cX cX cX],1:3);
count = count + 3;
end
end
end
%
function [oX,oY] = func1(rX,rY)
C1 = 1000;
C2 = 1200;
C3 = 1500;
C4 = 1700;
oX = C1 + (C3 - C1) * ((rX - 1) / (W - 1));
oY = C2 + (C4 - C2) * ((rY - 1) / (H - 1));
end
(更新)好的,我从循环中取出函数,现在这部分使用向量计算,速度更快
[rX,rY] = meshgrid(1:W,1:H);
[oX,oY] = func1(rX,rY);
现在代码如下所示:
%
A = rand(3,3);
H = 1200;
W = 1500;
S = rand(H,W,3,'uint8')
R = zeros(H,W,3,'uint8');
lIR = zeros(1,H*W*3);
lIC = zeros(1,H*W*3);
count = 0;
[rX,rY] = meshgrid(1:W,1:H);
[oX,oY] = func1(rX,rY);
for j = 1:1:H
for i = 1:1:W
cP = A*[oX(i); oY(j); 1];
cP = cP / cP(3);
c = round(cP);
if cp(1) < size(S,2) && cp(1) > 1 && cp(2) < size(S,1) && cp(2) > 1
lIR(count+1:count+3) = sub2ind([size(R) 1],[rY rY rY], [rX rX rX],1:3);
lIC(count+1:count+3) = sub2ind([size(S) 1],[cY cY cY],[cX cX cX],1:3);
count = count + 3;
end
end
end
%
function [oX,oY] = func1(rX,rY)
C1 = 1000;
C2 = 1200;
C3 = 1500;
C4 = 1700;
oX = C1 + (C3 - C1) * ((rX - 1) / (W - 1));
oY = C2 + (C4 - C2) * ((rY - 1) / (H - 1));
end
我还尝试制作内部函数 sub2ind 的优化版本:
function ndx = sub2ind_optimized(siz,varargin)
siz = double(siz);
numOfIndInput = nargin-1;
k = [1 siz(1) siz(1)*siz(2)];
ndx = 1;
for i = 1:numOfIndInput
v = varargin{i};
ndx = ndx + (v-1)*k(i);
end
这部分代码仍然很慢......