Anyone can help me to improve this code?
조회 수: 1 (최근 30일)
이전 댓글 표시
Dear friends; I have a code which is not suitable for big matrices or unlimited matrice. I would like to make it better because some times i have a very big matrices such as A = (100,100)
A = zeros(n,n) matrix.
R = [ 0 0 0 1 1] vector
c=2
if R(5,1) == 1
A(5,5) = c
A(5,4) = - c
A(4,5) = - c
else
A(5,5) = 0
A(5,4) = 0
A(4,5) = 0
end
if R(4,1) == 1
A(4,4) = c + A(5,5)
A(3,4) = - c
A(4,3) = - c
else
A(4,4) = 0
A(3,4) = 0
A(4,3) = 0
end
.
.
.
ans
A =
0 0 0 0 0
0 0 0 0 0
0 0 0 -2 0
0 0 -2 4 -2
0 0 0 -2 2
Thanks in advance, your help always appreciated
댓글 수: 0
채택된 답변
Andrei Bobrov
2013년 5월 22일
편집: Andrei Bobrov
2013년 5월 22일
[EDIT]
n = 5; %
R = [0 0 0 1 1]';% eg
c = 2; %
A1 = spdiags(-c*R,1,n,n);
A = A1 + A1' + spdiags(c*(R + [R(2:end);0]),0,n,n);
full(A)
OR
Rin(:,[1 3 2]) = c*[-[circshift(R,-1) R],R + [R(2:end);0]];
A = spdiags(Rin,-1:1,n,n);
full(A)
OR
Rin(:,[1 3 2]) = c*[-[circshift(R,-1) R],conv(R,[1;1],'same')];
A = spdiags(Rin,-1:1,n,n);
full(A)
댓글 수: 3
추가 답변 (2개)
David Sanchez
2013년 5월 22일
Ii this what you need?
for k=1:n-1
if R(k,1) == 1
A(k,k)= c + A(k+1,k+1);
else
A(k,k) = A(k+1,k+1);
end
댓글 수: 4
David Sanchez
2013년 5월 22일
I see, you have to start the for loop by the end.
c=2;
if R(5,1) == 1
A(5,5) = c
A(5,4) = - c
A(4,5) = - c
else
A(5,5) = 0
A(5,4) = 0
A(4,5) = 0
end
for k=(n-1):-1:1
if R(k) == 1
A(k,k)= c + A(k+1,k+1);
else
A(k,k) = A(k+1,k+1);
end
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!