【问题标题】:Finding location of elements w.r.t original matrix after reshape in Matlab在Matlab中重塑后查找元素w.r.t原始矩阵的位置
【发布时间】:2014-05-23 13:39:23
【问题描述】:

我有一个 1*262144 矩阵,我已将其重新整形为 512*512 矩阵。现在,我需要第二个矩阵中的某些元素,并且想知道它们在原始行矩阵中的位置。说,我需要在我的重塑矩阵中位于 (256,4) 的元素。我怎样才能知道这个元素在我原来的仅行矩阵中的位置?

 matri_working_now = C(1,:);
    matrix_working_now = reshape(matri_working_now,512,512);
    [nrows,ncols] = size(matrix_stables);   %matrix_stables is a matrix over which I am looping over which contains the locations of the desired elements as per the reshaped matrix. this itself is a 30839*2 matrix
    for row = 1:nrows
        for col = 1:ncols
        %sub2ind(size(matrix_working_now),row,col)
        %fprintf('iteration is equal to %6.2f.\n',row,col);
        [rowss colum] = ind2sub(size(matri_working_now),sub2ind(size(matrix_working_now),matrix_stable(row),matrix_stable(col)));    % i am accessing the elements of matrix_stables which provide me the row and column numbers; 

        end
    end

有什么建议/想法吗?

谢谢!

【问题讨论】:

    标签: arrays matlab matrix reshape


    【解决方案1】:

    由于你的原始矩阵是一个向量,你只需要convert from subindices to linear indexsub2ind

    col = sub2ind(size(reshapedMatrix), 256,4);
    

    一般来说,如果原始矩阵不一定是向量,则需要第二步用ind2sub

    [row col] = ind2sub(size(originalMatrix), sub2ind(size(reshapedMatrix), 256,4));
    

    例子:

    >> originalMatrix = (1:10).^2
    originalMatrix =
         1     4     9    16    25    36    49    64    81   100
    
    >> reshapedMatrix = reshape(originalMatrix, 2,5)
    reshapedMatrix =
         1     9    25    49    81
         4    16    36    64   100
    
    >> reshapedMatrix(2,3)
    ans =
        36
    
    >> [row col] = ind2sub(size(originalMatrix), sub2ind(size(reshapedMatrix), 2,3))
    row =
         1
    col =
         6
    
    >> originalMatrix(row,col)
    ans =
        36
    

    【讨论】:

    • 我得到“超出范围的下标错误”;我正在重新发布我的完整代码以便更好地查看。
    • 请查看原帖中修改后的代码。谢谢!
    • @KashifNawaz 在您的sub2ind 行中,我认为您的尺寸互换了。与我的答案比较
    • 又出现同样的错误! matri_ 是我的原始矩阵; matrix_ 是我的重塑矩阵。否则,我没有明白你的意思。
    • 请参见上面的编辑代码。现在收到错误 Undefined function 'matrix_stable' for input arguments of 'double' 类型。我想我必须使用 mat2something 进行此更改,你认为哪一个?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    相关资源
    最近更新 更多