MATLAB: The sum of the loop elements

latitudelongitudeloopwhile

Welcome! First of all sorry for my english. I would like to calculate the average latitude between the individual elements of the loop.
fi_A=50.0;
lambda_A=35;
delta = 10;
i = 0;
lambda_z_i = lambda_A + i * delta;
while (lambda_z_i < 120)
i = i + 1;
lambda_z_i = lambda_A + i * delta;
fprintf('Longitude : %.4f \n', lambda_z_i);
r=(lambda_w)-(lambda_z_i);
fi_z_i= atand(tand(fi_w)*cosd(r));
fprintf('Latitude: %.4f \n', fi_z_i);
end
What do I mean exactly? The loop displays the results:
Longitude: 45.0000
Latitude: 56.3850
Longitude: 55.0000
Latitude: 61.2754
Longitude: 65.0000
Latitude: 64.4266
Longitude: 75.0000
Latitude: 66.4204
Longitude: 85.0000
Latitude: 67.5734
Longitude: 95.0000
Latitude: 68.0493
Longitude: 105.0000
Latitude: 67.9112
Longitude: 115.0000
Latitude: 67.1410
Longitude: 125.0000
Latitude: 65.6340
I would like to calculate:
First: (fi_A Latitude + Latitude 1 from the loop)/2: ---> 50+56.3850/2=53.1925
next: (Latitude 1 from the loop + Latitude 2 from the loop)/2 --->56.3850+61.2754=58.8302
next: (Latitude 2 from the loop + Latitude 3 from the loop)/2 --->61.2754+64.4266=62.8510
e.t.c.
How can i do this?

Best Answer

First of all you need to store the values of fi_z_i in every iteration, so that you end up with a vector consisting of all latitudes. Let's call this vector lats. To store values, add this line at the end of the loop.
lats(i)=fi_z_i
You may also want to learn about preallocating the variable lats, to make the code more effective.
Assuming you have this vector, you can then use conv() to calculate a moving average.
A=[fi_A lats];
weights=[1 1]/2; %use window of 2 elements and equal weights
B=conv(A,weights);
out=B(2:end-1)