function [ weight_vectors, SV_cell ] = svm_extract_weights( model )
%SVM_EXTRACT_WEIGHTS Extract weight vectors from a multi-class svm model
%   trained by libsvm;
%

n = model.nr_class;
d = size(model.SVs, 2);

w = cell(n,n);

SV_cell = cell(n,1);

% extract the support vectors for each class
sv_start = [0; cumsum(model.nSV)];
for c=1:n
    i = find(model.Label==c, 1);
    I = sv_start(i) + (1:model.nSV(i))';
    SV_cell{c} = model.SVs(I,:);
end

for c1=1:n
    for c2=1:n

        j = find(model.Label==c2, 1);
        
        if i==j
            w{i,j} = zeros(1,d);
        else
            I = sv_start(i) + (1:model.nSV(i))';
            J = sv_start(j) + (1:model.nSV(j))';
            
            j_relative_i = j - (i<j); % i is omitted from the list, so j's index is one less if i precedes j
            i_relative_j = i - (j<i);
            
            coef = [model.sv_coef(I,j_relative_i);
                    model.sv_coef(J,i_relative_j)];

                
            SVs = model.SVs([I; J], :);
            
            w{c1,c2} = sign(c2-c1)*coef'*SVs;
        end
        
    end
end

weight_vectors = cat(1, w{:});

end

