% session 2
clear all; clf







% drawing circles
n=30;
th=linspace(0,2*pi,n);
x=cos(th); y=sin(th);

nc=10000;
xx=randn(nc,1);
yy=randn(nc,1);
r=(randn(nc,1).^2/30);

disp('with krontrick')
% second way with array operations

tic
X=kron(r,[x'; NaN])+kron(xx,[ones(n,1);NaN]);
Y=kron(r,[y';NaN])+kron(yy,[ones(n,1);NaN]);

plot(X,Y,'k-');
axis equal tight
t1=toc

disp('with loop');
tic
for ind=1:nc;
    plot(r(ind)*x+xx(ind),r(ind)*y+yy(ind),'k-');
    hold on
end
axis equal tight
t2=toc



t2/t1



break

% auxiliary for 2D plots
n=30;
x=linspace(-2*pi,2*pi,n);
y=linspace(-2*pi,2*pi,n);

[X,Y]=meshgrid(x,y);

for t=linspace(0,4*pi,200);
    

f=sin(X*2-t).*exp(-X.^2/2-Y.^2/2);
mesh(X,Y,f);
ll=0.8;
zlim([-1,1]*ll);
caxis([-1,1]*ll);

drawnow;
end

break




% BINARISATION
a=imread('pingpong.png');
b=sum(a,3);


for lim=1:5:500
sel=b>lim;
c=b;
c(sel)=1;
c(~sel)=0;

imagesc(c);
colormap gray
drawnow
end



break


% logical operations

for n=2:1000:10000;

np=sum(rand(n,1)>0.5)/n;

plot(n,np,'r.',n,0.5,'k.');
hold on
end
ylim([0,1]);


break



% shifting subarrays
n=1000;
x=linspace(0,2*pi,n);
f=sin(x);
dx=x(2)-x(1);
I=sum(f(1:n-1)+f(2:n))*dx/2


break

% memory management
n=1000
disp('one by one')
tic
f=[];
for ind=1:n;
    f=[f,ind];
end
t1=toc



disp('all together');
tic;
for ind=1:n
f(ind)=ind;
end
t2=toc

t1/t2




break

% plotting example
n=1000;
x=randn(n,1);
y=randn(n,1);

disp('one by one');
tic;
for ind=1:n;
    plot(x(ind),y(ind),'k.');
    hold on;
end
t1=toc

clf;
disp('all together');
tic
plot(x,y,'k.');
t2=toc;

t1/t2





break
% exemple of vectorization
n=1000;
A=randn(n,n);
B=randn(n,n);

disp('function operation');
tic
C=A*B;
t1=toc

disp('with loops')
tic
C=zeros(n,n);
for i=1:n;
    for j=1:n;
        for k=1:n
            C(i,j)=A(i,k)*B(k,j);
        end
    end
end
t2=toc

t2/t1










