8eastFromThe3ast
8eastFromThe3ast

Reputation: 197

MATLAB reshape matrix converting indices to row index

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?

Upvotes: 1

Views: 672

Answers (1)

Oleg
Oleg

Reputation: 10676

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

Upvotes: 5

Related Questions