for loop grabs last element of array

조회 수: 8 (최근 30일)
Janvier Solaris
Janvier Solaris 2018년 6월 20일
댓글: Stephen23 2018년 6월 20일
Hi , I am working on a basic for loop example that I am going to apply to a more complex problem but I am running accross an issue. my for loop grabs the last element of my array
here is my basic code
N = [ 4 6 8 10];
M = N;
T = 2;
for k = 1 : length(M)
x = linspace(-20,20, M(k));
dt = T/N(k);
y = sin(x) + M(k);
yi = cos(x) + dt;
end
grid on
%plot (x, y, '-.', x,yi,'--')
result >> N
N =
Columns 1 through 3
4 6 8
Column 4
10
>> M(k)
ans =
10
My question is ....why is it that I am seeing the last value in the array instead of the first value. when I type M(k), shouldn't I see 4 instead of 10. I am going to be running some calculations that will be grabbing each value of the array in order and using it from 4 to 10 but this gives me the impression that it works backward and I can see how this is going to give me futre errors
Can anyone enlighten me on this? Thank You
  댓글 수: 1
Stephen23
Stephen23 2018년 6월 20일
"why is it that I am seeing the last value in the array instead of the first value."
Because that is what you wrote your code to do.
"when I type M(k), shouldn't I see 4 instead of 10."
Yes, but only on the first loop iteration. After the last loop iteration k will be 4 and of course M(4) is 10.

댓글을 달려면 로그인하십시오.

답변 (1개)

Ameer Hamza
Ameer Hamza 2018년 6월 20일
편집: Ameer Hamza 2018년 6월 20일
You are getting last value because you are writing this line after the loop is complete. At the end of the loop, the value of k is 4, hence it is showing the 4th element of M. Inside the for-loop, it will give each value one by one in order. In order to understand this, run your loop with the following change
for k = 1 : length(M)
disp(M(k)); % <----- show the value of 'M(k)' during each iteration
x = linspace(-20,20, M(k));
dt = T/N(k);
y = sin(x) + M(k);
yi = cos(x) + dt;
end

카테고리

Help CenterFile Exchange에서 Event Functions에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by