Storing the values of a for loop
Mostrar comentarios más antiguos
That is the line to increment ze from 0.1 to 1.2 in increments of 0.1. How do I store the values of ze?
for ze=0.1:0.1:1.2 end;
3 comentarios
Stephen23
el 12 de Feb. de 2018
ze = 0.1:0.1:1.2;
Aishwarya Bangalore Kumar
el 12 de Feb. de 2018
Stephen23
el 12 de Feb. de 2018
@Aishwarya Bangalore Kumar: it creates a vector ze with values from 0.1 to 1.2 in steps of 0.1.
Respuestas (1)
Star Strider
el 12 de Feb. de 2018
Assign ‘ze’ before the loop, then index with reference to it:
ze = 0.1:0.1:1.2;
for k = 1:numel(ze)
v(k) = % DO SOMETHING
end
8 comentarios
Aishwarya Bangalore Kumar
el 12 de Feb. de 2018
Star Strider
el 12 de Feb. de 2018
What are you doing in the loop?
This approach avoids defining ‘ze’ in the loop. Defining ‘ze’ before the loop allows you to use it anywhere in your code.
If you want to use elements of ‘ze’ in your calculations in the loop, just refer to them with subscripts:
ze = 0.1:0.1:1.2;
for k = 1:numel(ze)
v(k) = ze(k)^2;
end
Aishwarya Bangalore Kumar
el 12 de Feb. de 2018
Star Strider
el 12 de Feb. de 2018
The loop here increments ‘ze’ with every iteration of the ‘k’ loop.
Aishwarya Bangalore Kumar
el 12 de Feb. de 2018
Star Strider
el 12 de Feb. de 2018
You do not need a loop to create or increment ‘ze’. This code does it automatically:
ze = 0.1:0.1:1.2;
Also, the colon (link) operator creates ‘ze’ in a way that minimises the errors that occur in floating-point calculations. A loop that begins from 0.1 and increments by 0.1 to 1.2 would propagate, rather than minimise, those errors.
Aishwarya Bangalore Kumar
el 12 de Feb. de 2018
Star Strider
el 12 de Feb. de 2018
As always, my pleasure!
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!