How can I call the first value from a for loop into a vector?
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
James Tursa
2018-2-10
编辑:James Tursa
2018-2-10
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
2018-2-10
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!