我开发了一个函数来减小初始向量X = [x,y]
的大小。但对于X
500,000点和points_limit = 10000
,Matlab需要16秒才能完成此功能。
有没有办法优化这个,可能是通过使用矩阵运算(矢量化)去除循环?
function X = reduce_vector_size(X,points_limit)
while length(X) > points_limit
k = 1;
X2 = zeros(round(length(X(:,1))/2),2);
X = sortrows(X);
for i=1:2:length(X(:,1))-1
X2(k,1) = mean([X(i,1) ,X(i+1,1) ]);
X2(k,2) = mean([X(i,2) ,X(i+1,2) ]);
k = k + 1;
end
X = X2;
end
另一个最好的想法是采用新方法:
Ratio = ceil(length(X(:,1))/points_limit);
X = ceil(X);
X = sortrows(X,1);
X = sortrows(X,2);
X1=[];
for i=1:points_limit - 1
X1 = [X1; mean(X(i*Ratio:(i+1)*Ratio,1)), mean(X(i*Ratio:(i+1)*Ratio,2))];
end
X = X1;
目标是减少矢量中的点数:2D矢量的压缩函数形式。
你知道我是否可以用循环来做这个新方法吗?
您如何看待我的压缩算法?
答案 0 :(得分:1)
您可以轻松地对内部for循环进行矢量化:
k = 1;
X = rand(5e5,2);
X2 = zeros(round(length(X(:,1))/2),2);
tic
for i=1:2:length(X(:,1))-1
X2(k,1) = mean([X(i,1) ,X(i+1,1) ]);
X2(k,2) = mean([X(i,2) ,X(i+1,2) ]);
k = k + 1;
end
toc % Elapsed time is 1.988739 seconds.
tic
X3 = (X(1:2:length(X(:,1))-1,:) + X(2:2:length(X(:,1)),:))/2;
toc % Elapsed time is 0.014575 seconds.
isequal(X2,X3) % true