How to convert row to matrix with below format????

1 回表示 (過去 30 日間)
Yuvaraj Venkataswamy
Yuvaraj Venkataswamy 2018 年 6 月 6 日
I need to convert row to matrix. For example, A=[1 2 3 4 5]
Need answer like this, Ans=[1 0 0 0 0; 0 1 0 0 0; 0 0 1 0 0; 0 0 0 1 0; 0 0 0 0 1]
  7 件のコメント
Stephen23
Stephen23 2018 年 6 月 6 日
@Yuvaraj V: I have updated my answer to match your comment.
Yuvaraj Venkataswamy
Yuvaraj Venkataswamy 2018 年 6 月 6 日
@Stephen Cobeldick: Thank You so much

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

採用された回答

Stephen23
Stephen23 2018 年 6 月 6 日
編集済み: Stephen23 2018 年 6 月 6 日
>> A = [3,1,1,4];
>> N = numel(A);
>> Z = zeros(N);
>> Z(sub2ind([N,N],1:N,A)) = 1
Z =
0 0 1 0
1 0 0 0
1 0 0 0
0 0 0 1
EDIT: if my example is acceptable, as you now write, then you will need something like this:
>> A = [5,1,1,4];
>> R = numel(A);
>> C = max(A);
>> Z = zeros(R,C);
>> Z(sub2ind([R,C],1:R,A)) = 1
Z =
0 0 0 0 1
1 0 0 0 0
1 0 0 0 0
0 0 0 1 0
  1 件のコメント
Yuvaraj Venkataswamy
Yuvaraj Venkataswamy 2018 年 6 月 6 日
@Stephen Cobeldick: Thank You so much

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

その他の回答 (1 件)

Birdman
Birdman 2018 年 6 月 6 日
編集済み: Birdman 2018 年 6 月 6 日
Something like this should work:
A=[3 1 1 4];
Ans=zeros(max(size(A)));
r=1:max(size(A));
c=A;
idx=sub2ind(size(repmat(A,max(size(A)),1)),r,c);
Ans(idx)=1
  2 件のコメント
Stephen23
Stephen23 2018 年 6 月 6 日
編集済み: Stephen23 2018 年 6 月 6 日
@Birdman: there is a syntax error on this line:
Ans=zeros(max(size(A));
Birdman
Birdman 2018 年 6 月 6 日
編集済み: Birdman 2018 年 6 月 6 日
Yes there should be one more parenthesis. Thanks.

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

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by