简体   繁体   English

用matlab / octave'去旋转'矩阵

[英]'De-pivoting' a matrix in matlab/octave

I want to convert a matrix M into "tall-skinny" format. 我想将矩阵M转换为“高瘦”格式。 The resulting matrix would have rows like [r, c, M(r,c)] for every r and c in the rows and columns of M. Is there a function which does this? 对于M的行和列中的每个r和c,得到的矩阵将具有类似[r,c,M(r,c)]的行。是否有这样的函数? Alternatively, is there a function which does the reverse? 或者,是否有相反的功能?

Is this what you want? 这是你想要的吗?

[ii jj] = ndgrid(1:size(M,1), 1:size(M,2));
T = [ii(:) jj(:) M(:)];

Reverse: 相反:

M = full(sparse(T(:,1), T(:,2), T(:,3)));

or more simply, as noted by Jumppy89, 或更简单地说,如Jumppy89所述,

M = full(spconvert(T));

I am curious too if this would satisfy your needs - 如果能满足您的需求,我也很好奇 -

Normal to Tall-skinny (based on meshgrid ) - 从普通到高瘦(基于网meshgrid ) -

[x1,x2] = meshgrid(1:size(M,1),1:size(M,2))
TSM = [x2(:) x1(:) M(:)] %// Tall-Skinny M

Tall-skinny to Normal (based on sub2ind and reshaping) - 高瘦到正常(基于sub2ind和重塑) -

m1 = max(TSM(:,2))
n1 = max(TSM(:,1))
TSM3 = TSM(:,3)
M_out = reshape(TSM3(sub2ind([n1 m1],TSM(:,1),TSM(:,2))),m1,n1)

You can do it in a different way to Luis and Divakar, using sub2ind and ind2sub for the reverse. 您可以采用与Luis和Divakar不同的方式,使用sub2indind2sub进行反向操作。 I doubt this is a better solution than theirs though. 我怀疑这是比他们更好的解决方案。

To convert to the "tall-skinny" format: 要转换为“tall-skinny”格式:

M = [1     1     1
     1     2     2
     2     1     3
     2     2     4]
S=zeros([max(M(:,1)) max(M(:,2))])
I=sub2ind([max(M(:,1)) max(M(:,2))],M(:,1),M(:,2))
S(I)=M(:,3)

And the reverse: 反之亦然:

[r,c]=ind2sub(size(S),1:numel(S))
M=[r.' c.' S(:)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM