Filling a matrix using vectorization
2 ビュー (過去 30 日間)
古いコメントを表示
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
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.
採用された回答
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)
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!