Why does my resulting matrix only contain the last value of the iteration for p and q?

4 ビュー (過去 30 日間)
Celso Carranza
Celso Carranza 2018 年 4 月 23 日
コメント済み: Walter Roberson 2018 年 4 月 23 日
phi(1,1) = 3;
phi(2,1) = 2;
phi(3,1) = 1;
phi(5,1) = 6;
g = [1 2 3; 4 5 6; 7 8 9];
for j = [1,2,5]
for m = [1,2,5]
for p = 1:3
for q = 1:3
k(phi(j),phi(m)) = g(p,q);
end
end
end
end

回答 (1 件)

Walter Roberson
Walter Roberson 2018 年 4 月 23 日
Your destination
k(phi(j),phi(m))
does not change as p or q change, so each iteration of p and q, you are writing to the same output location, so the result is the same as if you had only done the final assignment.
  2 件のコメント
Celso Carranza
Celso Carranza 2018 年 4 月 23 日
編集済み: Walter Roberson 2018 年 4 月 23 日

If I were to relate j and m with p and q, for instance

phi(1,1) = 3;
phi(2,1) = 2;
phi(3,1) = 1;
phi(5,1) = 6;
g = [1 2 3; 4 5 6; 7 8 9];
for j = [1,2,5]
      for m = [1,2,3]
          p = j;
          q = m;
                  k(phi(j),phi(p)) = g(m,q);
      end
  end

The result still ends up if I were only doing the final assessment.

Walter Roberson
Walter Roberson 2018 年 4 月 23 日

You have

p = j

so when you do

k(phi(j),phi(p))

then that is the same as

k(phi(j), phi(j))

and as j is your outer loop, you are still ovewriting the same location for each m value.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by