Need help creating an array
조회 수: 2 (최근 30일)
이전 댓글 표시
I want to create the following array:
A = [-4 2 0 0 0; 2 -4 2 0 0; 0 2 -4 2 0; 0 0 2 -4 2; 0 0 0 2 -4];
' That's easy enough but I want to know if there is a way to make it neater, and also capable of being expanded to a higher number of rows.
So far I have tried: I = eye(5,5) .* -4
I = [-4 0 0 0 0; 0 -4 0 0 0; 0 0 -4 0 0; 0 0 0 -4 0; 0 0 0 0 -4];
Which is close, I guess. But need the two's in the columns aswell.
Thanks in advance
댓글 수: 0
채택된 답변
Roger Stafford
2015년 4월 3일
Do either of these two:
n = 10; % <-- you choose n
A = diag(-4*ones(n,1))+diag(2*ones(n-1,1),1)+diag(2*ones(n-1,1),-1);
or
n = 10; % <-- you choose n
t = [-4,2,zeros(1,n-2)];
A = toeplitz(t,t);
댓글 수: 0
추가 답변 (1개)
James Tursa
2015년 4월 3일
편집: James Tursa
2015년 4월 3일
And another way:
A = full(spdiags(repmat([2 -4 2],n,1),[-1 0 1],n,n));
And yet another way:
A = -4*eye(n);
A(2:n+1:end) = 2;
A(n+1:n+1:end) = 2;
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!