Create a diagonal matrix with a for loop from a vector

조회 수: 15 (최근 30일)
Nathan Clark
Nathan Clark 2023년 4월 1일
편집: Adam Danz 2023년 4월 1일
I want to use the ML vector to create a diagonal matrix of only the values of the ML vector on the diagonal and make a new ML matrix with zeros everywhere else and the values of the ML vector along the diagonal of the new ML matrix. Essentially I am trying to write the code for diag(ML).
ML = rand([5 1])
for j = 1:length(ML)
for i = 1:j
if i < j
ML(i,j) == 0
elseif i > j
ML(i,j) == 0
else
ML(i,j) = ML(j)
end
end
end

채택된 답변

Dyuman Joshi
Dyuman Joshi 2023년 4월 1일
편집: Dyuman Joshi 2023년 4월 1일
(If you are required to use a loop)
It is better to use another variable to get an output.
ML = rand([5 1])
ML = 5×1
0.7725 0.4016 0.8767 0.9691 0.1817
Pre-allocate output matrix according to the size.
%Using max() in case ML is a row vector
Mout = zeros(max(size(ML)))
Mout = 5×5
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
%You can also obtain the result without double for loop
for j = 1:numel(ML)
%Directly define the values
Mout(j,j)=ML(j);
end
Mout
Mout = 5×5
0.7725 0 0 0 0 0 0.4016 0 0 0 0 0 0.8767 0 0 0 0 0 0.9691 0 0 0 0 0 0.1817

추가 답변 (1개)

Adam Danz
Adam Danz 2023년 4월 1일
편집: Adam Danz 2023년 4월 1일
Here are three way to define a diagonal in a square matrix of zeros that do not require a loop.
eye()
ML = rand([5 1])
ML = 5×1
0.2650 0.0656 0.8188 0.8268 0.6532
Mout = eye(numel(ML)).*ML
Mout = 5×5
0.2650 0 0 0 0 0 0.0656 0 0 0 0 0 0.8188 0 0 0 0 0 0.8268 0 0 0 0 0 0.6532
Indexing with sub2ind
n = numel(ML);
Mout = zeros(n);
ind = sub2ind([n,n],1:n,1:n);
Mout(ind) = ML
Mout = 5×5
0.2650 0 0 0 0 0 0.0656 0 0 0 0 0 0.8188 0 0 0 0 0 0.8268 0 0 0 0 0 0.6532
Indexing without sub2ind
This shortcut works because we're working with a square matrix.
n = numel(ML);
Mout = zeros(n);
Mout(1:n+1:end) = ML
Mout = 5×5
0.2650 0 0 0 0 0 0.0656 0 0 0 0 0 0.8188 0 0 0 0 0 0.8268 0 0 0 0 0 0.6532
  댓글 수: 1
Dyuman Joshi
Dyuman Joshi 2023년 4월 1일
I wonder if this is also the implementation in diag(input) or diag(input,0)

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

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by