Filter löschen
Filter löschen

for loop grabs last element of array

7 Ansichten (letzte 30 Tage)
Janvier Solaris
Janvier Solaris am 20 Jun. 2018
Kommentiert: Stephen23 am 20 Jun. 2018
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 Kommentar
Stephen23
Stephen23 am 20 Jun. 2018
"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.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Ameer Hamza
Ameer Hamza am 20 Jun. 2018
Bearbeitet: Ameer Hamza am 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

Community Treasure Hunt

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

Start Hunting!

Translated by