Vectorized implementation for using a vector as an index for matrices

1 回表示 (過去 30 日間)
Redouane Mohamed El Ghali CHADOULI
Redouane Mohamed El Ghali CHADOULI 2019 年 12 月 3 日
回答済み: Stephen23 2019 年 12 月 3 日
Hello, I have a culumn vector V of m numbers from 1 to 10.
I would like to crate a m x 10 matrix A where in each line i, the V(i) th element is set to 1 and rest to 0.
here's an example of the code I'm trying to vectorize :
A = zeros(m,10);
for i=1:m
A(v(i))=1;
end

採用された回答

Stephen23
Stephen23 2019 年 12 月 3 日
Use sub2ind like this:
>> m = 7;
>> V = randi([1,10],1,m)
V =
9 10 2 10 7 1 3
>> A = zeros(m,10);
>> A(sub2ind(size(A),1:m,V)) = 1
A =
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 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 1 0 0 0 0 0 0 0
>>

その他の回答 (0 件)

カテゴリ

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