Google
COMSOL Modelling: 04/01/2011 - 05/01/2011

Wednesday, April 13, 2011

Code for Making a Coil in MATLAB

I have been asked several times how did I generated the Coil in FEMLAB. I created the coil in MATLAB and then imported it as an object in FEMLAB. I was able to dig out the code and here it is for those who might still be interested.

function g = coil(h,r,s,n)
% Create a Coil Line Geometry Object
%
% Usage:
% g = coil(h,r,s,n)
%
% Arguments:
% h : height
% r : radius
% s : number of windings
% n : number of line segments per winding
% if n is not specified a spline is used to construct the coil
%
% Example:
% g = coil(0.1, 0.05, 5)
% geomplot(g)
%
% The coil is imported into FEMLAB by using the
% File->Import->Geometry Objects menu

if nargin==4
N = n*s;

carr = {};
for i=1:N
t = 2*pi*(i-1)/n;
x = r*cos(t);
y = r*sin(t);
z = h/N*(i-1);

t2 = 2*pi*i/n;
x2 = r*cos(t2);
y2 = r*sin(t2);
z2 = h/N*i;

carr{end+1} = curve3([x x2], [y y2], [z z2]);
end

g = geomcoerce('curve',carr);

else
n = 4;
N = n*s;

p = zeros(3,N+3);
t = 2*pi*(-0.1)/n;
x = r*cos(t);
y = r*sin(t);
z = h/N*(-0.1);
p(:,1) = [x y z]';
for i=1:N+1
t = 2*pi*(i-1)/n;
x = r*cos(t);
y = r*sin(t);
z = h/N*(i-1);

p(:,i+1) = [x y z]';
end
t = 2*pi*(N+0.1)/n;
x = r*cos(t);
y = r*sin(t);
z = h/N*(N+0.1);
p(:,N+3) = [x y z]';

g = geomspline(p);

end