Storing all values into an array

So I'm working on this code to help me with a class, and it works except for the fact that it doesn't store all of my x answers into the array, it only stores the last one. Any suggestions would be so helpful, oh I'm using the R2012a on a macbook pro (don't really know if you need this info)
n = 1;
x = 0;
for n = 1:365
w = 45;
B = (n-1)*(360/365);
d = (180/pi)*(0.006918-00.399912*cos(B)+0.070257*sin(B)-0.006758*cos(2*B)+0.000907*sin(2*B)-0.002697*cos(3*B)+0.00148*sin(3*B));
c = x;
x = sin(d)* sin(o)*cos(t) - sin(d)*cos(o)*sin(t)*cos(s) + cos(d)*cos(o)*cos(t)*cos(w) + cos(d)*sin(o)*sin(t)*cos(s)*cos(w) + cos(d)*sin(t)*sin(s)*sin(w);
%plot (d,x);
A = [45 x]
end
n = n+1;

 Accepted Answer

Jos (10584)
Jos (10584) on 24 Feb 2015
Edited: Jos (10584) on 25 Feb 2015
You want to do something like this:
N = 10 ;
A = zeros(N,1) ; % pre-allocation, will speeds things up
for k=1:N,
x = rand(1) + 3 ; % some calculation
A(k) = x ; % store it
end
However, note that in matlab you can often vectorise loops. All of the lines above vectorises into:
A = rand(10,1)+3 ;

2 Comments

Thank you! It works perfectly
@Leah Aguirre: the vectorized solution is the one you should use! And you should learn about how to write your own vectorized code too.

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!