Create a diagonal matrix with a for loop from a vector
9 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Nathan Clark
am 1 Apr. 2023
Bearbeitet: Adam Danz
am 1 Apr. 2023
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
0 Kommentare
Akzeptierte Antwort
Dyuman Joshi
am 1 Apr. 2023
Bearbeitet: Dyuman Joshi
am 1 Apr. 2023
(If you are required to use a loop)
It is better to use another variable to get an output.
ML = rand([5 1])
Pre-allocate output matrix according to the size.
%Using max() in case ML is a row vector
Mout = zeros(max(size(ML)))
%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
0 Kommentare
Weitere Antworten (1)
Adam Danz
am 1 Apr. 2023
Bearbeitet: Adam Danz
am 1 Apr. 2023
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])
Mout = eye(numel(ML)).*ML
Indexing with sub2ind
n = numel(ML);
Mout = zeros(n);
ind = sub2ind([n,n],1:n,1:n);
Mout(ind) = ML
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
1 Kommentar
Dyuman Joshi
am 1 Apr. 2023
I wonder if this is also the implementation in diag(input) or diag(input,0)
Siehe auch
Kategorien
Mehr zu Operating on Diagonal Matrices finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!