indexing an entire for loop
28 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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
0 Kommentare
Akzeptierte Antwort
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
am 18 Feb. 2019
Thank you for the help. A couple of follow up questions:
- 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?
- 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
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.
Weitere Antworten (1)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!