N=50;
n=N/2;
randn('state',6);
x1=randn(2,n);
y1=ones(1,n);
x2=5+randn(2,n);
y2=-ones(1,n-1);
y2(1,n)=1;
figure;
plot(x1(1,:),x2(2,:),'b*',x2(1,1:n-1),x2(2,1:n-1),'k.',...
    x2(1,n),x2(2,n),'b*');
axis([-3 8 -3 8]);
hold on
X1=[x1,x2];
Y1=[y1,y2];
X=X1';
y=Y1;
x=X;
C=50;
[g,z,a,k,d,m]=matlabsvm1(C,X,y,x)
a0=a';
for i =1:size(k,2)
    if a0(k(i))~=C
        plot(X(k(i),1),X(k(i),2),'s')
    elseif a0(k(i))==C
        plot(X(k(i),1),X(k(i),2),'ro')
    end
end
pp=-3:0.1:8;
A=sum(a.*(y').*X(:,2));
B=sum(a.*(y').*(X*(X(k(1),:))'))-y(k(1))-sum(a.*(y').*X(:,1))*pp;
E=B+1;
F=B-1;
t1=B/A;
t2=E/A;
t3=F/A;
plot(pp,t1,'r',pp,t2,'--',pp,t3,'--')
%X,y表示学习样本
%X是N*(p-1)矩阵，y是1*N矩阵
%x是未知样本，q*N矩阵
%k表示支持向量以及错分向量所在位值
%m1表示支持向量所在位值
%d是margin
function [gg,zz,a,k,d,m1]=matlabsvm1(C,X,y,x)
N=size(X,1);
p=size(X,2)+1;

%%%%%%%  产生、加载学习样本 %%%%%%%
for i=1:N
    yy(:,i)=[X(i,:),y(i)]';
end
qq=yy';
save data.dat qq -ASCII -TABS
%%%%%%%%%  优化拉格朗日乘子 %%%%%%%%%
aa=rand(N,1);        %拉格朗日乘子初始值
%lb=zeros(N,1);
ub=C*ones(N,1);
fun=@myfun;
con=@mycon;
%a=fmincon('myfun',aa,[],[],[],[],[],ub,'mycon');
a=fmincon(fun,aa,[],[],[],[],[],ub,con);

%%%%%%%% 构造分类函数 %%%%%%%%%
k=argk(a');
a0=a';
m1=zeros(1,size(k,2));
for i=1:size(k,2)
    if a0(k(i))~=C
        m1(i)=k(i);
    end
end
q=size(x,1);
for m=1:q
    for n=1:N
        u1(n)=neiji(X(n,:),x(m,:));
        u2(n)=neiji(X(n,:),X(k(1),:));
        g(n,m)=a(n)*y(n)*u1(n)-a(n)*y(n)*u2(n)+y(k(1))/N;
    end
end
gg=sum(g);

%%%%%%%% 分类 %%%%%%%%%%
for i=1:q
    if gg(i)>0
       zz(i)=1;
    elseif gg(i)<0
        zz(i)=-1;
    end
end

%%%%%%%%% 求解margin %%%%%%%%%
for i=1:N
    d1(i,:)=a(i)*y(i)*X(i,:);
end
d2=sum(d1);
d=2/sqrt(d2*d2');

%%%%%%%%% 子函数 %%%%%%%%%%%%%
function u=neiji(A,B)
u=sum(A.*B);
%%%%%%%%%%%%%%
function k=argk(z)
N=size(z,2);
m=0;
for i=1:N
    if z(i)>1e-5
        m=m+1;
        k(m)=i;
    end
end
%%%%%%%%%%%%%
function f=myfun(a)
load data.dat;
N=size(data,1);
m=size(data,2)-1;
for t=1:N
    for n=1:N
        %u(t,n)=neiji(data(t,1:m),data(n,1:m));
        %q(n,t)=a(t,1)*a(n,1)*data(t,m+1)*data(n,m+1)*u(t,n);
        q(n,t)=a(t,1)*a(n,1)*data(t,m+1)*data(n,m+1)*sum(data(t,1:m).*data(n,1:m));
    end
end
qq=sum(q);
f=1/2*sum(qq)-sum(a);
%%%%%%%%%%
function [c,ceq]=mycon(a)
load data.dat;
[N,n]=size(data);
for i=1:N
    s(i)=a(i,1)*data(i,n);
end
c=-a';
ceq=sum(s);
        运行后出现所有函数都应以end结束提示，怎么改