How to set elements in 2D matrix based on a given vector?

Hi,
I have a zeros array [0 0 0;0 0 0;0 0 0] and a vector [3;1;2]. I want to have an array [0 0 1;1 0 0;0 1 0]. Is it possible to do that using only indexing and slicing instead of for-loop? Thanks.

 採用された回答

Atsushi Ueno
Atsushi Ueno 2021 年 6 月 5 日

1 投票

x = zeros(3);
y = [3;1;2];
x(sub2ind(size(x),1:size(x,1),y')) = 1;

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by