Vectorize a double loop

1 回表示 (過去 30 日間)
AC
AC 2021 年 5 月 10 日
コメント済み: Walter Roberson 2021 年 5 月 13 日
Hi everyone
I'm tryng to vectorize the folowing piece of code:
n=30;
d=3;
a=1;
b=2;
cell=3;
for ki = 2:n-1
for kj = 2:n-1
M((cell-1)*n^2+(ki-1)*n+kj,(cell-1)*n^2+(ki-1)*n+kj-1) = 1/d^2;
M((cell-1)*n^2+(ki-1)*n+kj,(cell-1)*n^2+(ki-1)*n+kj) = -4/d^2-a;
M((cell-1)*n^2+(ki-1)*n+kj,(cell-1)*n^2+(ki-1)*n+kj+1) = 1/d^2;
M((cell-1)*n^2+(ki-1)*n+kj,(cell-1)*n^2+(ki-1)*n+kj-n) = 1/d^2;
M((cell-1)*n^2+(ki-1)*n+kj,(cell-1)*n^2+(ki-1)*n+kj+n) = 1/d^2;
C((cell-1)*n^2+(ki-1)*n+kj,1) = b;
end
end
How can I do it? I will appreciate any help! Thanks!
  3 件のコメント
Walter Roberson
Walter Roberson 2021 年 5 月 10 日
(cell-1)*n^2+(ki-1)*n+kj
You are faking 4 dimensional indexing. You should switch to actual 4D indexing. reshape() before and after if you need to.
Walter Roberson
Walter Roberson 2021 年 5 月 13 日
If you feel that your post is unclear, then since you are the one who wrote it, you should clarify it.

サインインしてコメントする。

回答 (1 件)

Bob Thompson
Bob Thompson 2021 年 5 月 10 日
Does this work? I haven't been able to test it.
M((cell-1)*n^2+(1:n-2)*n+(2:n-1),(cell-1)*n^2+(1:n-2)*n+(2:n-1)-1) = 1/d^2;
M((cell-1)*n^2+(1:n-2)*n+(2:n-1),(cell-1)*n^2+(1:n-2)*n+(2:n-1)) = -4/d^2-a;
M((cell-1)*n^2+(1:n-2)*n+(2:n-1),(cell-1)*n^2+(1:n-2)*n+(2:n-1)+1) = 1/d^2;
M((cell-1)*n^2+(1:n-2)*n+(2:n-1),(cell-1)*n^2+(1:n-2)*n+(2:n-1)-n) = 1/d^2;
M((cell-1)*n^2+(1:n-2)*n+(2:n-1)j,(cell-1)*n^2+(1:n-2)*n+(2:n-1)+n) = 1/d^2;
C((cell-1)*n^2+(1:n-2)*n+(2:n-1),1) = b;
  1 件のコメント
AC
AC 2021 年 5 月 10 日
Thank you for your answer! I tried this, but didn't work. When using the double for loop, I get (n-2)*(n-2) combinations of ki's and kj's. But (cell-1)*n^2+(1:n-2)*n+(2:n-1) is a vector of length (n-2). I need a vector of length (n-2)*(n-2)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by