indexing an entire for loop

28 Ansichten (letzte 30 Tage)
Matthew Henry
Matthew Henry am 18 Feb. 2019
Bearbeitet: madhan ravi am 18 Feb. 2019
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

Akzeptierte Antwort

madhan ravi
madhan ravi am 18 Feb. 2019
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 Kommentare
madhan ravi
madhan ravi am 18 Feb. 2019
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 am 18 Feb. 2019
Bearbeitet: madhan ravi am 18 Feb. 2019
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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

madhan ravi
madhan ravi am 18 Feb. 2019
No loops needed:
T = x.^2.' + 2*y.^2

Kategorien

Mehr zu Loops and Conditional Statements 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