automatically filling a matrix

18 visualizaciones (últimos 30 días)
bus14
bus14 el 22 de Mayo de 2019
Editada: Stephen23 el 9 de Ag. de 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!

Respuesta aceptada

Stephen23
Stephen23 el 22 de Mayo de 2019
Editada: Stephen23 el 9 de Ag. de 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 comentario
bus14
bus14 el 22 de Mayo de 2019
Great thanks for your help

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by