优化无循环矩阵的重组

时间:2019-03-15 03:10:49

标签: matlab for-loop matrix optimization reorganize

TL; DR :我正在尝试在Matlab中优化以下简短代码。因为它涉及到大型矩阵上的循环,所以它太慢了。

for i = 1:sz,
    for j = 1:sz,
        if X(j) == Q(i) && Y(j) == R(i),
            S(i) = Z(j);
            break
        end
    end
end

特技:基本上,我从要绘制为表面的x,y和z数据的三个向量开始。我生成了x和y数据的网格,然后使用

为相应的z值制作了矩阵
[X, Y] = meshgrid(x, y);
Z = griddata(x, y, z, X, Y);

由于数据是按随机顺序收集的,因此在生成曲面图时,连接都是错误的,并且该图看起来都是三角剖分的,如下例所示。enter image description here

因此,为确保Matlab连接正确的点,我随后使用重组了X和Y矩阵

[R, R_indx] = sort(Y);
[Q, Q_indx] = sort(X, 2);

从这里开始,我认为这将是根据矩阵X和Y的排序索引重新组织矩阵Z的简单问题。但是我遇到了麻烦,因为无论如何使用索引,我都无法产生正确的矩阵。例如,我尝试过

S = Z(R_indx); % to match the rearrangement of Y
S = S(Q_indx); % to match the rearrangement of X

我得到了这个条形码... enter image description here

运行第一段代码可以得到如图所示的“所需”结果。但是,这要花很长时间,因为它是一个很大的矩阵上的双循环。enter image description here

问题:如何在没有for循环的情况下优化矩阵Z的重新排列?

1 个答案:

答案 0 :(得分:1)

请查看以下解决方案,并使用您的矩阵进行测试。他们执行得更快吗? 数组索引解决方案可以满足您的要求,即矩阵的重新排列。 向量索引可能更好,因为它对原始向量进行排序而不是对矩阵进行排序,并直接从那里生成输出。

% Parameters.
dim = 4;

% Test input.
x = [2, -2, 5, 4];
y = [1, -4, 6, -2];
z = rand(dim);
[X, Y] = meshgrid(x, y);
Z = griddata(x, y, z, X, Y);
[R, R_indx] = sort(Y);
[Q, Q_indx] = sort(X, 2);

% Initialize output.
S = zeros(dim);

% Provided solution using loop.
for i = 1:numel(z)
  for j = 1:numel(z)
    if (X(j) == Q(i) && Y(j) == R(i))
      S(i) = Z(j);
      break
    end
  end
end

% Output.
S

% Solution using array indexing; output.
S_array = reshape(((X(:) == Q(:).') & (Y(:) == R(:).')).' * Z(:), dim, dim)

% Solution using vector indexing; output.
[r, r_indx] = sort(y);
[q, q_indx] = sort(x);
[X, Y] = meshgrid(q, r);
Z = griddata(q, r, z, X, Y);
idx = (ones(dim, 1) * ((q_indx - 1) * dim) + r_indx.' * ones(1, dim));
S_vector = Z(idx)

示例输出:

S = 
   0.371424   0.744220   0.777214   0.778058
   0.580353   0.686495   0.356647   0.577780
   0.436699   0.217288   0.883900   0.800133
   0.594355   0.405309   0.544806   0.085540

S_array =
   0.371424   0.744220   0.777214   0.778058
   0.580353   0.686495   0.356647   0.577780
   0.436699   0.217288   0.883900   0.800133
   0.594355   0.405309   0.544806   0.085540

S_vector =
   0.371424   0.744220   0.777214   0.778058
   0.580353   0.686495   0.356647   0.577780
   0.436699   0.217288   0.883900   0.800133
   0.594355   0.405309   0.544806   0.085540