Effacer les filtres
Effacer les filtres

automatically filling a matrix

16 vues (au cours des 30 derniers jours)
bus14
bus14 le 22 Mai 2019
Modifié(e) : Stephen23 le 9 Août 2019
Hi community,
n=200;
i=3;
j=6;
I want to create a matrix which fills a matrix of (n*j) x j and has in the first column -1 for the first n numbers and the rest zeros and for the second column n zeros,n -ones and for the rest zeros again.
I created one manually for the following situation of n=200;i=3;j=6; However, I want to create a script in which I can increase the values of n,i,j and Matlab automatically generates a new correct matrix. Does anyone know how to do this?
My own code is
% when n=200; i=3; and j=6;
AX1= [-ones(n,1);zeros(5*n,1)];
AX2= [zeros(n,1);-ones(n,1);zeros(4*n,1)];
AX3= [zeros(2*n,1);-ones(n,1);zeros(3*n,1)];
AX4= [zeros(3*n,1);-ones(n,1);zeros(2*n,1)];
AX5= [zeros(4*n,1);-ones(n,1);zeros(n,1)];
AX6= [zeros(5*n,1);-ones(n,1)];
AX=[AX1,AX2,AX3,AX4,AX5,AX6];
Thanks in advance!

Réponse acceptée

Stephen23
Stephen23 le 22 Mai 2019
Modifié(e) : Stephen23 le 9 Août 2019
Method one: eye and kron:
>> n = 5;
>> j = 6;
>> M = kron(-eye(j),ones(n,1))
M =
-1 0 0 0 0 0
-1 0 0 0 0 0
-1 0 0 0 0 0
-1 0 0 0 0 0
-1 0 0 0 0 0
0 -1 0 0 0 0
0 -1 0 0 0 0
0 -1 0 0 0 0
0 -1 0 0 0 0
0 -1 0 0 0 0
0 0 -1 0 0 0
0 0 -1 0 0 0
0 0 -1 0 0 0
0 0 -1 0 0 0
0 0 -1 0 0 0
0 0 0 -1 0 0
0 0 0 -1 0 0
0 0 0 -1 0 0
0 0 0 -1 0 0
0 0 0 -1 0 0
0 0 0 0 -1 0
0 0 0 0 -1 0
0 0 0 0 -1 0
0 0 0 0 -1 0
0 0 0 0 -1 0
0 0 0 0 0 -1
0 0 0 0 0 -1
0 0 0 0 0 -1
0 0 0 0 0 -1
0 0 0 0 0 -1
Method two: eye and repelem:
>> M = repelem(-eye(j),n,1)
M =
-1 0 0 0 0 0
-1 0 0 0 0 0
-1 0 0 0 0 0
-1 0 0 0 0 0
-1 0 0 0 0 0
0 -1 0 0 0 0
0 -1 0 0 0 0
0 -1 0 0 0 0
0 -1 0 0 0 0
0 -1 0 0 0 0
0 0 -1 0 0 0
0 0 -1 0 0 0
0 0 -1 0 0 0
0 0 -1 0 0 0
0 0 -1 0 0 0
0 0 0 -1 0 0
0 0 0 -1 0 0
0 0 0 -1 0 0
0 0 0 -1 0 0
0 0 0 -1 0 0
0 0 0 0 -1 0
0 0 0 0 -1 0
0 0 0 0 -1 0
0 0 0 0 -1 0
0 0 0 0 -1 0
0 0 0 0 0 -1
0 0 0 0 0 -1
0 0 0 0 0 -1
0 0 0 0 0 -1
0 0 0 0 0 -1
Method three: blkdiag and a comma separated list:
>> C = {-ones(n,1)};
>> M = blkdiag(C{ones(1,j)})
M =
-1 0 0 0 0 0
-1 0 0 0 0 0
-1 0 0 0 0 0
-1 0 0 0 0 0
-1 0 0 0 0 0
0 -1 0 0 0 0
0 -1 0 0 0 0
0 -1 0 0 0 0
0 -1 0 0 0 0
0 -1 0 0 0 0
0 0 -1 0 0 0
0 0 -1 0 0 0
0 0 -1 0 0 0
0 0 -1 0 0 0
0 0 -1 0 0 0
0 0 0 -1 0 0
0 0 0 -1 0 0
0 0 0 -1 0 0
0 0 0 -1 0 0
0 0 0 -1 0 0
0 0 0 0 -1 0
0 0 0 0 -1 0
0 0 0 0 -1 0
0 0 0 0 -1 0
0 0 0 0 -1 0
0 0 0 0 0 -1
0 0 0 0 0 -1
0 0 0 0 0 -1
0 0 0 0 0 -1
0 0 0 0 0 -1
  1 commentaire
bus14
bus14 le 22 Mai 2019
Great thanks for your help

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by