Filling a matrix using vectorization

조회 수: 2 (최근 30일)
Haydar Dyab
Haydar Dyab 2020년 9월 3일
댓글: Haydar Dyab 2020년 9월 3일
Hello, I am trying to fill specific indices of a matrix, and I am using a for loop to do this, here is a small example code snippet:
r=2;
for s = 2:119
nnum(r,s)=(r-1)*120+s;
M(nnum(r,s),nnum(r,s)-1) = -1;
M(nnum(r,s),nnum(r,s)+1) = -2;
M(nnum(r,s),nnum(r,s)-120) = -3;
M(nnum(r,s),nnum(r,s)+120) = -4;
M(nnum(r,s),nnum(r,s)) = 5;
end
Now I have a big program with a lot of operations like the one above, and I wanted to reduce the computation time by using the vectorization to fill my matrices. Here is the code I tried:
r=2;
s = 2:119;
k=(r-1)*120+s;
F(k,k-1) = -1;
F(k,k+1) = -2;
F(k,k-120) = -3;
F(k,k+120) = -4;
F(k,k) = 5;
Now I thought that F and M would be equal but they are not. The thing is that I want only the first element of the vector in the first matrix index to couple with the first element of the vector in the second matrix index and so on. What is happening here is thet each element of the vector is coupling with all the elements from the other vector to form indices. Any ideas on how I can achieve the first code snippet without the use of a for loop?
  댓글 수: 2
Nikita Agrawal
Nikita Agrawal 2020년 9월 3일
편집: Nikita Agrawal 2020년 9월 3일
These two are not same because the code runs in a sequential order and you are overwriting some cells in everystep in F. For eg: [k,k-1] & [k,k+1] could be same for many k when k is a variable.
Haydar Dyab
Haydar Dyab 2020년 9월 3일
Yeah I knew the problem but couldn't find a way to solve it, thanks anw!

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

채택된 답변

Rik
Rik 2020년 9월 3일
The problem is that this:
A([1 2],[1 3])
returns 4 positions, not two. If you want two instead, you will need to convert subindices to linear indices:
ind=sub2ind(size(A),[1 2],[1 3]);
A(ind)
  댓글 수: 1
Haydar Dyab
Haydar Dyab 2020년 9월 3일
Yeah using linear indices works. Thanks!!

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by