Matlab 无环变换矩阵

Matlab 无环变换矩阵,matlab,for-loop,Matlab,For Loop,我有oldMat,这是股票行情的排名。列号表示各自的等级,例如,第一列等于最高等级,第二列表示第二最高等级,依此类推。oldMat中的整数表示单个股票代码的编号。oldMat(3,2,1)中的数字3表示第三个股票代码在第三个期间排名第二(行代表不同的期间) 现在,我需要以以下方式转换oldMat:现在列号表示单个股票行情。现在,整数代表了个别股票报价人在特定时期的排名。例如,newMat(3,3,1)中的数字2意味着第三个股票代码在第三个时段排名第二 为了解决这个问题,我使用了for循环,但我确

我有
oldMat
,这是股票行情的排名。列号表示各自的等级,例如,第一列等于最高等级,第二列表示第二最高等级,依此类推。
oldMat
中的整数表示单个股票代码的编号。
oldMat(3,2,1)
中的数字
3
表示第三个股票代码在第三个期间排名第二(行代表不同的期间)

现在,我需要以以下方式转换
oldMat
:现在列号表示单个股票行情。现在,整数代表了个别股票报价人在特定时期的排名。例如,
newMat(3,3,1)
中的数字
2
意味着第三个股票代码在第三个时段排名第二

为了解决这个问题,我使用了for循环,但我确信有一种更有效的方法来实现这个结果。这是我的密码:

% Define oldMat
oldMat(:,:,1) = ...
    [NaN, NaN, NaN, NaN, NaN, NaN; ...
    1, 3, 4, 6, 2, 5; ...
    6, 3, 4, 1, 2, 5; ...
    2, 3, 6, 1, 4, 5; ...
    5, 4, 6, 2, 3, 1; ...
    5, 1, 2, 3, 6, 4; ...
    4, 5, 1, 3, 6, 2; ...
    4, 1, 6, 5, 2, 3];
oldMat(:,:,2) = ...
    [NaN, NaN, NaN, NaN, NaN, NaN; ...
    NaN, NaN, NaN, NaN, NaN, NaN; ...
    1, 6, 3, 4, 2, 5; ...
    6, 3, 2, 1, 4, 5; ...
    2, 6, 3, 4, 1, 5; ...
    5, 2, 1, 6, 3, 4; ...
    5, 1, 3, 6, 2, 4; ...
    4, 1, 5, 6, 3, 2];

% Pre-allocate newMat
newMat = nan(size(oldMat));

% Transform oldMat to newMat
for runNum = 1 : size(newMat,3)

    for colNum = 1 : size(newMat,2)

        for rowNum = 1 : size(newMat,1)
            if ~isnan(oldMat(rowNum, colNum, runNum))
                newMat(rowNum,oldMat(rowNum, colNum, runNum), runNum) = colNum;
            end
        end

    end

end

看起来像是一个典型的案例。您希望创建一组线性索引来访问新矩阵的第二维度,并将其设置为等于列号。首先使用创建三维坐标网格,然后使用
oldMat
矩阵作为输出第二列的索引,并将其设置为列号。确保不要复制任何
NaN
值,或者
sub2ind
会投诉。您可以使用来帮助筛选这些值:

% Initialize new matrix
newMat = nan(size(oldMat));

% Generate a grid of coordinates
[X,Y,Z] = meshgrid(1:size(newMat,2), 1:size(newMat,1), 1:size(newMat,3));

% Find elements that are NaN and remove
mask = isnan(oldMat);
X(mask) = []; Y(mask) = []; Z(mask) = [];

% Set the values now
newMat(sub2ind(size(oldMat), Y, oldMat(~isnan(oldMat)).', Z)) = X;