MATLAB reshape matrix converting indices to row index

眉间皱痕 提交于 2019-12-11 05:37:39

问题


Is it possible to reshape matrices such that

x1 = 
    1   5
    3   4
    4   3
    7   1

becomes

x2 =
    5
    NaN
    4
    3
    NaN
    NaN
    1

or vice versa, where the first column in x1 is an index that corresponds to a row# in x2?


回答1:


Create an array with NaNs and fill it with values:

x2          = NaN(max(x1(:,1)),1);
x2(x1(:,1)) = x1(:,2);

Now, if zero padding is acceptable, then you can simply use the second line directly without first creating out.

Alternatively, for your specific example (no overlapping indices) the same result is achieved with:

accumarray(x1(:,1),x1(:,2),[],[],NaN)

Going the other way

idx = ~isnan(x2);
x1  = [find(idx) x2(idx)];


来源:https://stackoverflow.com/questions/16196250/matlab-reshape-matrix-converting-indices-to-row-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!