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

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 Exchange에서 Loops 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