for loop grabs last element of array

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 Comment

"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.

Sign in to comment.

Answers (1)

Ameer Hamza
Ameer Hamza on 20 Jun 2018
Edited: Ameer Hamza on 20 Jun 2018
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

Categories

Asked:

on 20 Jun 2018

Commented:

on 20 Jun 2018

Community Treasure Hunt

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

Start Hunting!