How to add an entry to a vector after each iteration of a loop?

3 views (last 30 days)
I want to calculate a number inside a loop n times and append each calculation to a row vector each time. How can I do this?

Answers (1)

Star Strider
Star Strider on 24 Oct 2015
One possibility:
n = 10;
for k1 = 1:n
number(k1) = exp(k1/10);
end
You will have to define what ‘calculate a number’ means, and code it appropriately. (I did a random calculation here to illustrate the approach.) The ‘number’ vector in this syntax is a row vector (the MATLAB default), so it satisfies your requirement.
  2 Comments
CGN
CGN on 24 Oct 2015
Sorry for being so vague. I don't know how many iterations the loop needed to run until the loop is done running. Each iteration of the loop I calculate an error and I want to be able to store each individual error from each loop iteration in a vector.
Star Strider
Star Strider on 24 Oct 2015
Without more information I cannot provide specific code or even a relevant example.
However it would be most appropriate for you to use a while loop. See for an example Implementing a while loop into my code? for a way to do this correctly. You will of course have to make appropriate changes in your code to do the calculation you want, but this example illustrates the appropriate syntax.

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!