%This script draws a parametric curve - in this case, a circle - 
%of radius 3  - and computes its length.

clear; %clear all variables before doing anything

%First, we write a parametrization of the circle, that is, we write
%the coordinates (x,y) of a point on a circle as functions of a parameter t

x = @(t) 3*cos(t);
y = @(t) 3*sin(t);

%Now this is a periodic curve: it re-traces itself as t increases.
%The common period of the two functions above is 2*pi, so to trace
%the curve, we need to let t go from 0 to 2*pi.

t = [0:0.1:2*pi];

%Now we evaluate x, y on t to get lists of coordinates 

X = x(t); %MATLAB is case-sensitive, so X and x are different variables
Y = y(t);

%This can be sent to the plot command. NOTE: you can't call plot(x,y),
%since x and y here are FUNCTIONS, not DATA! 

plot(X, Y)
axis equal

%What we plotted is a broken line consisting of segments with endpoints
%at (X(1), Y(1)), (X(2), Y(2)), (X(3), Y(3)),..

%Now we compute the length of what we just plotted. To do so, we use 
%the formula for length of a segment from (x0, y0) to (x1, y1):
%L = sqrt((x1-x0)^2 + (y1-y0)^2)

%To calculate the length of ALL segments at once, we use the diff
%command to get successive differences:

dX = diff(X); %dX now contains [(X(2)-X(1)) (X(3)-X(2)) (X(4)-X(3)) ...]
dY = diff(Y); %dY now contains [(Y(2)-Y(1)) (Y(3)-Y(2)) (Y(4)-Y(3)) ...]

%Now we get the list of lengths of all segments

lengths = sqrt(dX.^2 + dY.^2);

%Note: 
%  lengths(i) = sqrt( {X(i+1) - X(i)}^2  + {Y(i+1) - Y(i)}^2 )
%             = sqrt( {x(t(i+1)) - x(t(i))}^2  + {y(t(i+1)) - y(t(i))}^2 )

% To get the total length, we sum the list with the sum command

L=sum(lengths)

% Run the script, and check the answer - should be 6*pi, the length
% of the circle of radius 3. If you get a slightly different answer,
% think how to improve it!

% Without all the explanations, this computation can be done in one line:
% L=sum( sqrt( diff(x(t)).^2 + diff(y(t)).^2 ) )
%
% or, using the variables as defined above,
% L = sum( sqrt( dX.^2  + dY.^2 ) ) 