How can I call the first value from a for loop into a vector?
6 views (last 30 days)
Show older comments
After the for loop runs, I need to create a vector that displays all of the output from the for loop along with the first value of each variable (a=0 & b=1). How can I add the first value of a and b to the beginning of the vector?
a = 0;
b = 1;
for i = 1:20
c = a+b;
a = b;
b = c;
q(i) = c;
end
vec = q;
0 Comments
Answers (2)
James Tursa
on 10 Feb 2018
Edited: James Tursa
on 10 Feb 2018
Remember the starting values prior to the loop. E.g.,
A = a;
B = b;
Then after the loop concatenate:
vec = [A,B,q];
To avoid inadvertently including the q values from past runs, pre-allocate q prior to the loop. E.g.,
n = 20;
q = zeros(1,n);
for i = 1:n
:
There are also ways to do this using only one vector and doing everything with just indexing, avoiding the a = b and b = c stuff. E.g., an outline
n = 20;
vec = zeros(1,n);
vec(1) = 0;
vec(2) = 1;
for i=3:n
vec(i) = __________; % some expression of previous vec values
end
I will leave it to you to figure out what goes in the blank above.
Peter
on 10 Feb 2018
This seems like a homework question, so I won't give you complete code for it, but I will give you a few hints. If you want an array at the end, you will want to initialize q to how wide you want. Something like
q= [0 0 0];
Then you can append the values that you want on the end of that array with each iteration. Something like
q = ([q; a b c]);
If you want a cell array, then you could just do
q{i} = [a b c];
With each iteration.
0 Comments
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!