Is there a way to vectorize the definition of this matrix ?

3 ビュー (過去 30 日間)
Abdelhamid AHAJJAM
Abdelhamid AHAJJAM 2019 年 12 月 14 日
コメント済み: Turlough Hughes 2019 年 12 月 15 日
I am defining the matrix z this way :
z=zeros(n,m);
for i=1:n
for j=1:m
z(i,j)= i==y(j);
end
end
where y is a vector of size m. Is there a better way to write this ? (one line maybe)

採用された回答

Turlough Hughes
Turlough Hughes 2019 年 12 月 14 日
編集済み: Turlough Hughes 2019 年 12 月 15 日
Here's one way to do it in one line:
z = y.*ones(n,m)==(1:n).'.*ones(n,m);
I tested with the following inputs:
y=1:10;
n=5; m=length(y);
z = y.*ones(n,m)==(1:n).'.*ones(n,m);
edit: following stephens comment.
  2 件のコメント
Stephen23
Stephen23 2019 年 12 月 15 日
Note that square brackets are a concatentation operator, and should be replaced with grouping parentheses (exactly as the hint in the MATLAB editor also tells you):
(1:n)
It is a good habit to use transpose instead of conjugate transpose (unless you really need the conjugate transpose):
(1:n).'
Turlough Hughes
Turlough Hughes 2019 年 12 月 15 日
Thanks Stephen.

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

その他の回答 (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