How to map a value of a vector into column number of a matrix?

3 ビュー (過去 30 日間)
Mushahid Shamim
Mushahid Shamim 2018 年 1 月 31 日
コメント済み: Jan 2018 年 2 月 1 日
let A=[2;4;5] vector I want a matrix where all the values will be zero and the 2nd 4th and 5th element of column of 10x3 matrix will be 1.
B=[0 0 0
1 0 0
0 0 0
0 1 0
0 0 1
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0 ]

採用された回答

Jan
Jan 2018 年 1 月 31 日
A = [2, 4, 5];
B = zeros(10, 3);
idx = sub2ind(size(B), A, 1:3);
B(idx) = 1;
  4 件のコメント
Jos (10584)
Jos (10584) 2018 年 2 月 1 日
this seems to be a new question ...
Jan
Jan 2018 年 2 月 1 日
@Jos: I assume, Mushahid means the "1:3" from "sub2ind(size(B), A, 1:3)".

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

その他の回答 (2 件)

Andrei Bobrov
Andrei Bobrov 2018 年 2 月 1 日
n = numel(A);
B = accumarray([A(:),(1:n)'],1,[10,n]);

Jos (10584)
Jos (10584) 2018 年 2 月 1 日
A fast and easy one-liner from the old days, when accumarray did not exist :)
A = [2 ; 4 ; 5]
B = full(sparse(A, 1:numel(A), 1, 10, 3))

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by