%%
% Example 1.1.1
clc
clear all
close all
x=[2 9 3 12 9];
y=[5 6 7 8 9];
mean(x)
mean(y)
std(x)
std(y)
median(x)
median(y)
%%
% Example 1.1.2
z=[13 0 7 10 8 7 2 9 20 11]
length(z)
sort(z)
median(z)
%%
% Ex. 1.1.3
clc
clear all
close all

rain_sp=[50 48 55 44 47 13 8 18 39 78 60 55];
rain_ma=[62 42 70 35 35 4 1 3 32 94 71 56];
rain_lo=[58 39 51 49 54 53 48 56 58 62 61 63];

N_sp=length(rain_sp)
N_ma=length(rain_ma)
N_lo=length(rain_lo)
% mean
mean_sp=sum(rain_sp)/N_sp
% compare it with
mean(rain_sp)

mean_ma=sum(rain_ma)/N_ma
% compare it with
%mean(rain_ma)


mean_lo=sum(rain_lo)/N_lo
% compare it with
%mean(rain_lo)

% standard deviation
sigma_sp=sqrt( sum((rain_sp-mean_sp).^2)/(N_sp-1) )
% compare with
std(rain_sp)

% standard deviation
sigma_ma=sqrt( sum((rain_ma-mean_ma).^2)/(N_ma-1) )
% compare with
std(rain_ma)

% standard deviation
sigma_lo=sqrt( sum((rain_lo-mean_lo).^2)/(N_lo-1) )
% compare with
std(rain_lo)

% median

% separate the definition depending wheather N is odd or even

rain_sp_2=sort(rain_sp)

if mod(N_sp,2)==0
    median_sp=( rain_sp_2(floor(N_sp/2))+...
        rain_sp_2(floor(N_sp/2)+1) )/2;
else
    median_sp=rain_sp_2(floor((N_sp-1)/2)+1);
end

median_sp
% compare with
median(rain_sp_2)
% or
median(sort(rain_sp))

%%
% Ex. 1.1.4
clc
clear all
close all

rain_sp=[50 48 55 44 47 13 8 18 39 78 60 55];
rain_ma=[62 42 70 35 35 4 1 3 32 94 71 56];
rain_lo=[58 39 51 49 54 53 48 56 58 62 61 63];

N_sp=length(rain_sp);
N_ma=length(rain_ma);
N_lo=length(rain_lo);

% 4 bins with 3 elements in each bin
for i=1:4
    for j=1:3
        if((i-1)*3+j+2<=N_sp)
            % the generic element is (i-1)*3+j
            sp_bin(i,j)=rain_sp( (i-1)*3+j+2 );
            ma_bin(i,j)=rain_ma( (i-1)*3+j+2 );
            lo_bin(i,j)=rain_lo( (i-1)*3+j+2 );
        else
            sp_bin(i,j)=rain_sp( (i-1)*3+j+2-12 );
            ma_bin(i,j)=rain_ma( (i-1)*3+j+2-12 );
            lo_bin(i,j)=rain_lo( (i-1)*3+j+2-12 );
        end
    end
end
sp_bin

for i=1:4   
    % mean in each bin
    mean_sp(i)=sum(sp_bin(i,:))/3;
    % or equivalently
    mean_sp_2(i)=mean(sp_bin(i,:));
    
    %standard deviation in each bin
    st_dev_sp(i)=sqrt( sum((sp_bin(i,:)-mean_sp(i)).^2 )/(3-1) )
    % or equivalently
    st_dev_sp_2(i)=std(sp_bin(i,:));
    
    % same for other cities
    mean_ma(i)=sum(ma_bin(i,:))/3;
    st_dev_ma(i)=sqrt( sum((ma_bin(i,:)-mean_ma(i)).^2 )/(3-1) )
    
    mean_lo(i)=sum(lo_bin(i,:))/3;
    st_dev_lo(i)=sqrt( sum((lo_bin(i,:)-mean_lo(i)).^2 )/(3-1) )
end
mean_sp
mean_sp_2
st_dev_sp
st_dev_sp_2

i=(1:1:4);

% plot
hold on
errorbar(i,mean_sp,st_dev_sp/2,'-r','Linewidth',2)
errorbar(i,mean_ma,st_dev_ma/2,'--b','Linewidth',2)
errorbar(i,mean_lo,st_dev_lo/2,'-.g','Linewidth',2)
legend('spain','madrid', 'london', ...
    'Location','NorthWest')
xlabel('season','fontsize',16),ylabel('average rainfall [mm]',...
    'fontsize',16)
hold off
print -f -depsc 'Fig_binning.eps'







