automatically filling a matrix

15 Ansichten (letzte 30 Tage)
bus14
bus14 am 22 Mai 2019
Bearbeitet: Stephen23 am 9 Aug. 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!

Akzeptierte Antwort

Stephen23
Stephen23 am 22 Mai 2019
Bearbeitet: Stephen23 am 9 Aug. 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

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by