Append vector into zero matrix

13 visualizzazioni (ultimi 30 giorni)
H Lange
H Lange il 17 Nov 2021
Commentato: H Lange il 17 Nov 2021
So I have a zero matrix where I wish to insert the same vector into each column of the matrix, but for each column it need to be displaced one row, so that the vectors 'start' in the diagonal of the matrix. For instance if we have the vector v = [v_1, v_2, v_3], the matrix should look as following:
How would you implement this?
So far I have written the following code (the matrix is a NxM matrix):
for i=1:N
for j=1:M
???
end
end
The loop also needs to work for other vectors that has more than 3 elements.

Risposta accettata

Chunru
Chunru il 17 Nov 2021
v = zeros(5, 3);
x = randn(3,1);
n = numel(x);
for i=1:size(v, 2)
v(i-1+(1:n), i) = x;
end
v
v = 5×3
1.0525 0 0 1.3620 1.0525 0 0.0952 1.3620 1.0525 0 0.0952 1.3620 0 0 0.0952

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Prodotti


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by