Storing the values of a for loop
Mostra commenti meno recenti
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 Commenti
Stephen23
il 12 Feb 2018
ze = 0.1:0.1:1.2;
Aishwarya Bangalore Kumar
il 12 Feb 2018
Stephen23
il 12 Feb 2018
@Aishwarya Bangalore Kumar: it creates a vector ze with values from 0.1 to 1.2 in steps of 0.1.
Risposte (1)
Star Strider
il 12 Feb 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 Commenti
Aishwarya Bangalore Kumar
il 12 Feb 2018
Star Strider
il 12 Feb 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
il 12 Feb 2018
Star Strider
il 12 Feb 2018
The loop here increments ‘ze’ with every iteration of the ‘k’ loop.
Aishwarya Bangalore Kumar
il 12 Feb 2018
Star Strider
il 12 Feb 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
il 12 Feb 2018
Star Strider
il 12 Feb 2018
As always, my pleasure!
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!