1
votes

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

1 Answers

5
votes

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)];