Append vector into zero matrix

9 vues (au cours des 30 derniers jours)
H Lange
H Lange le 17 Nov 2021
Commenté : H Lange le 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.

Réponse acceptée

Chunru
Chunru le 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
  1 commentaire
H Lange
H Lange le 17 Nov 2021
That works perfectly, thank you so much!!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by