Hello, I'm looking for some help with a function I've made to return the Frenet-Serret vectors for a 'track' defined by a set of x,y,z coordinates. It seems to work except for the curvature which is certainly wrong. I've tested it with a simple unit circle and the curvature is 0.01, not 1. Any help would be much appreciated.

Thanks

Code:

function [T,N,B,k,t] = frenet(x,y,z),
% Frenet - Serret Vecotrs
% T = Tangent
% N = Normal
% B = Binormal
% k = curvature
% t = torsion
% If only x and y inputted, set z to all zeros
if nargin == 2,
z = zeros(size(x));
end
% If x, y and z are row vectors, make them colums
x = x(:);
y = y(:);
z = z(:);
%Set up a dr vector
dx = gradient(x);
dy = gradient(y);
dz = gradient(z);
dr = [dx dy dz];
% The tangent vector
for i=1:size(x)
T(i,:) = dr(i,:)/norm(dr(i,:),2);
end
dTx = gradient(T(:,1));
dTy = gradient(T(:,2));
dTz = gradient(T(:,3));
dT = [dTx dTy dTz];
% The Normal vecotr
for j=1:size(x)
N(j,:) = dT(j,:)/norm(dT(j,:),2);
end
% The binormal vector
B = cross(T,N);
dBx = gradient(B(:,1));
dBy = gradient(B(:,2));
dBz = gradient(B(:,3));
dB = [dBx dBy dBz];
% Curvature
for i=1:length(x)
k(i) = norm(dT(i,:),2);
t(i) = norm(dB(i,:),2);
end