将一维数组重塑为网格格式

Reshape 1D arrays to meshgrid format

我将数据 xyzv 组织为列向量。类似的数据可以通过下面的代码获取:

N = 5;
[xf,yf,zf,vf] = flow(N);
ux = unique(xf);
uy = unique(yf);
uz = unique(zf);

x = nan(numel(xf),1);
y = nan(numel(yf),1);
z = nan(numel(zf),1);
v = nan(numel(vf),1);
iCount = 1;
for iX = 1:numel(ux)
    for iY = 1:numel(uy)
        for iZ = 1:numel(uz)
            x(iCount) = ux(iX);
            y(iCount) = uy(iY);
            z(iCount) = uz(iZ);
            v(iCount) = vf((xf == x(iCount))&(yf == y(iCount))&(zf == z(iCount)));
            iCount = iCount+1;
        end
    end
end

我无法更改数据生成方式,因此我需要对其进行整形以供稍后使用 isosurface()griddedInterpolant()。原始数据的大小相当大,我想避免循环。 reshape()函数的简单用法:

X = reshape(x,[N,2*N,N]);
Y = reshape(y,[N,2*N,N]);
Z = reshape(z,[N,2*N,N]);
V = reshape(v,[N,2*N,N]);
isosurface(X,Y,Z,V,-3)

告诉我,Input grid is not a valid MESHGRID.

你能帮我以适当的方式重塑数据吗?

您数组中项目的顺序与来自 meshgrid 的列优先顺序不匹配。您几乎完成了,但是您需要用不同的形状重塑一维数组,然后将结果置换回您需要的实际形状:

N = 5;
[xf,yf,zf,vf] = flow(N);
ux = unique(xf);
uy = unique(yf);
uz = unique(zf);

x = nan(numel(xf),1);
y = nan(numel(yf),1);
z = nan(numel(zf),1);
v = nan(numel(vf),1);
iCount = 1;
for iX = 1:numel(ux)
    for iY = 1:numel(uy)
        for iZ = 1:numel(uz)
            x(iCount) = ux(iX);
            y(iCount) = uy(iY);
            z(iCount) = uz(iZ);
            v(iCount) = vf((xf == x(iCount))&(yf == y(iCount))&(zf == z(iCount)));
            iCount = iCount+1;
        end
    end
end

% new stuff starts here
X = permute(reshape(x,[N,N,2*N]),[2,3,1]);
Y = permute(reshape(y,[N,N,2*N]),[2,3,1]);
Z = permute(reshape(z,[N,N,2*N]),[2,3,1]);
V = permute(reshape(v,[N,N,2*N]),[2,3,1]);

% check equivalence
isequal(X,xf)
isequal(Y,yf)
isequal(Z,zf)
isequal(V,vf)

上面表示输入数组被复制(我们得到四个逻辑1s)。

请注意,您的测试用例应该更加不对称,因为现在一些输入数组是彼此的转置,并且三个维度中的两个具有相同的大小。如果您使用不对称大小进行测试,即 [N,M,K],则更容易找出可能的歧义,因为在这种情况下所有维度都是不等价的:

N = 2; M = 3; K = 4;
[xf,yf,zf] = meshgrid(1:N,1:M,1:K);
vf = flow(xf,yf,zf);

ux = unique(xf);
uy = unique(yf);
uz = unique(zf);

x = nan(numel(xf),1);
y = nan(numel(yf),1);
z = nan(numel(zf),1);
v = nan(numel(vf),1);
iCount = 1;
for iX = 1:numel(ux)
    for iY = 1:numel(uy)
        for iZ = 1:numel(uz)
            x(iCount) = ux(iX);
            y(iCount) = uy(iY);
            z(iCount) = uz(iZ);
            v(iCount) = vf((xf == x(iCount))&(yf == y(iCount))&(zf == z(iCount)));
            iCount = iCount+1;
        end
    end
end

X = permute(reshape(x,[K,M,N]),[2,3,1]);
Y = permute(reshape(y,[K,M,N]),[2,3,1]);
Z = permute(reshape(z,[K,M,N]),[2,3,1]);
V = permute(reshape(v,[K,M,N]),[2,3,1]);

% check equivalence
isequal(X,xf)
isequal(Y,yf)
isequal(Z,zf)
isequal(V,vf)