Create a logical matrix from numerical vector

Maybe the title sounds vague, but I'll try to explain. I have the following vector of size samples-by-1 that contains the numerical values between 0 and 9 (10 values):
V = [3;5;1;2;6;9;7;8;4;0]
Now I want to create a 'logical' matrix from this. So like this:
0 1 2 3 4 5 6 7 8 9
M = [0 0 0 1 0 0 0 0 0 0;
0 0 0 0 0 1 0 0 0 0;
0 1 0 0 0 0 0 0 0 0;
0 0 1 0 0 0 0 0 0 0;
0 0 0 0 0 0 1 0 0 0;
0 0 0 0 0 0 0 0 0 1;
0 0 0 0 0 0 0 1 0 0;
0 0 0 0 0 0 0 0 1 0;
0 0 0 0 1 0 0 0 0 0;
1 0 0 0 0 0 0 0 0 0]
What's the easiest way to achieve this?

 採用された回答

Walter Roberson
Walter Roberson 2017 年 12 月 18 日

2 投票

full( ind2vec(V+1).' )
or,
accumarray((1:length(V)).', V+1)
or
maxV = max(V);
LV = length(V);
M = zeros(LV, maxV+1);
M(V * LV + (1:LV).') = 1;
or
maxV = max(V);
LV = length(V);
M = zeros(LV, maxV+1);
M( sub2ind(size(M), (1:LV).', V+1) ) = 1;

3 件のコメント

YT
YT 2017 年 12 月 18 日
編集済み: YT 2017 年 12 月 18 日
Tested with V is a 70.000-by-1 vector
  • solution 1, didn't work (Error using ind2vec, The data is not a row vector or cell array of row vectors)
  • solution 2, returned samples-by-1 vector with values 1-10.
  • solution 3/4, worked. Returned samples-by-10 matrix with values 0/1
Thanks for the fast responses (@all)
Walter Roberson
Walter Roberson 2017 年 12 月 18 日
full( ind2vec(V.'+1).' )
or
accumarray([(1:length(V)).', V+1], 1)
YT
YT 2017 年 12 月 18 日
Easy fix I see. Thanks!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

質問済み:

YT
2017 年 12 月 18 日

コメント済み:

YT
2017 年 12 月 18 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by