creating a repeating diagonal matrix

42 vues (au cours des 30 derniers jours)
Josue Lujan
Josue Lujan le 8 Sep 2020
Modifié(e) : Muhammad Fiaz le 24 Jan 2022
I'm trying to create a diagonal matrix with the following sequence on the main diagonal line where v is the vector v=[4,1,0,1] to get the following matrix
[4 0 0 0 0 0 0
0 1 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 1 0 0 0
0 0 0 0 4 0 ...]
but I want it to repeat the same sequence over an over again for a 100 by 100 matrix how would I be able to do this?
  1 commentaire
Muhammad Fiaz
Muhammad Fiaz le 24 Jan 2022
Can you do it?
Please I also need help..

Connectez-vous pour commenter.

Réponse acceptée

John D'Errico
John D'Errico le 8 Sep 2020
Modifié(e) : John D'Errico le 8 Sep 2020
You want to repeat that sequence on the main diagonal?
v = [4 1 0 1];
A = diag(repmat(v,1,25));
That is, use repmat to replicate the sequece 25 times. Then use diag to create the associated diagonal matrix.
If you wanted the matrix to be a sparse matrix, you would use spdiags to form the matrix.
v = [4;1;0;1];
A = spdiags(repmat(v,25,1),0,100,100);
In the second form, I used spdiags. We can visualize the matrix as created using spy.
spy(A)
A dot is shown for all non-zero elements. You can even visualize those zero elements on the diagonal, because no dots were shown there.
  2 commentaires
Josue Lujan
Josue Lujan le 8 Sep 2020
yes i wanted to repeat the sequence on the main diaginal thank you!
Muhammad Fiaz
Muhammad Fiaz le 24 Jan 2022
Modifié(e) : Muhammad Fiaz le 24 Jan 2022
Can we repeat matrix is tri-diagnally?
e.g
[1 2 3 4]
I want to make it [1 2 0 0 0 0 ; 3 4 0 0 0 0 ; 0 0 1 2 0 0 ; 0 0 3 4 0 0 ; 0 0 0 0 1 2; 0 0 0 0 3 4]

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Sparse Matrices dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by