filling each row of a matrix using values from a vector

조회 수: 1 (최근 30일)
Nora Khaled
Nora Khaled 2019년 7월 30일
댓글: Nora Khaled 2019년 7월 30일
Hello !
I want to fell certine element in a matrix in this way:
for example matrix x=[0 0 0 0 ; 0 0 0 0 ; 0 0 0 0 ];
and then I have vector u= [1;4;3;3]
I want to use the number of in u to make x like this x=[1 0 0 0; 0 0 0 1; 0 0 1 0; 0 0 1 0];
since the first row of u contain 1 then the first row of x in the first colunm chnage to one.
and the 2nd row = 4 then x(2,4)=1.. and so one.
is there a way to do this with out loops ?
  댓글 수: 1
James Tursa
James Tursa 2019년 7월 30일
Can we assume x starts with the proper size? In this case a 4x4 instead of the 3x4 shown.

댓글을 달려면 로그인하십시오.

채택된 답변

James Tursa
James Tursa 2019년 7월 30일
Assuming x starts as a 4x4 matrix (instead of a 3x4 matrix):
x(sub2ind(size(x),(1:numel(u))',u)) = 1;
  댓글 수: 1
Nora Khaled
Nora Khaled 2019년 7월 30일
Thank you!
Although the assumption is not applicable in my case however this code seems to work.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by