Filling a matrix using vectorization

2 Ansichten (letzte 30 Tage)
Haydar Dyab
Haydar Dyab am 3 Sep. 2020
Kommentiert: Haydar Dyab am 3 Sep. 2020
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 Kommentare
Nikita Agrawal
Nikita Agrawal am 3 Sep. 2020
Bearbeitet: Nikita Agrawal am 3 Sep. 2020
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 am 3 Sep. 2020
Yeah I knew the problem but couldn't find a way to solve it, thanks anw!

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Rik
Rik am 3 Sep. 2020
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)

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Produkte


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by