필터 지우기
필터 지우기

automatically filling a matrix

조회 수: 17 (최근 30일)
bus14
bus14 2019년 5월 22일
편집: Stephen23 2019년 8월 9일
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!

채택된 답변

Stephen23
Stephen23 2019년 5월 22일
편집: Stephen23 2019년 8월 9일
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
bus14
bus14 2019년 5월 22일
Great thanks for your help

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by