Hi all. Embarassed to be asking for homework help, but I can't figure out this for loop.
Essentially, I need each iteration of the inner function to save to the matrix T. The size of the matrix remains correct (61x21), but it only saves the last iteration to the matrix. I have tried the i = i+1 indexing method but my matrix blows up to 1281x21 with each column running thru both the inner and outer loops.
clear;
x = -3:0.1:3;
y = -1:0.1:1;
i = length(x);
j = length(y);
T = zeros(i,j);
for x = -3:0.1:3
for y = -1:0.1:1
T(i,j) = x^2+(2*y^2);
end
end

 採用された回答

madhan ravi
madhan ravi 2019 年 2 月 18 日

0 投票

x = -3:0.1:3;
y = -1:0.1:1;
ii = length(x);
jj = length(y);
T = zeros(ii,jj);
for k = 1:ii
for l = 1:jj
T(k,l) = x(k)^2+(2*y(l)^2);
end
end

2 件のコメント

madhan ravi
madhan ravi 2019 年 2 月 18 日
Matthew Henry's answer moved here:
Thank you for the help. A couple of follow up questions:
  1. Does the function call to x and y still for it's values or to k and l? Or do k and l only specify the array index to save the iterated value?
  2. If I were to adapt this to a 3d matrix, would I only need to declare the 3rd dimension of that matrix?
Like, if there was a 3rd term using 'z' variable, it would be like this:
x = -3:0.1:3;
y = -1:0.1:1;
z = -2:0.1:2;
ii = length(x);
jj = length(y);
mm = length(z);
T = zeros(ii,jj,mm);
for k = 1:ii
for l = 1:jj
for n = 1:mm
T(k,l,n) = x(k)^2+(2*y(l)^2)+(3*z(n)^2);
end
end
end
Where ii,jj,mm declare the size of the T matrix, and k,l,n do the actual indexing?
madhan ravi
madhan ravi 2019 年 2 月 18 日
編集済み: madhan ravi 2019 年 2 月 18 日
Answering both questions together :
Yes k,l and n do the actual indexing, we do this because the indices in MATLAB has to start from 1 (not less than or equal to zero). I suggest you to do MATLAB onramp course MATLAB onramp course which is interactive and fun to learn MATLAB.

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

その他の回答 (1 件)

madhan ravi
madhan ravi 2019 年 2 月 18 日

0 投票

No loops needed:
T = x.^2.' + 2*y.^2

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

リリース

R2018b

質問済み:

2019 年 2 月 18 日

編集済み:

2019 年 2 月 18 日

Community Treasure Hunt

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

Start Hunting!

Translated by