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
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)

更多回答(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