How to add an entry to a vector after each iteration of a loop?
3 views (last 30 days)
Show older comments
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?
0 Comments
Answers (1)
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
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.
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!