function mat2libsvm(X,nclass,outFname) % Usage: mat2libsvm(X,nclass,outFname) % % previously named: f_toLibsvmFormat.m % convert the traditional training/testing data format (X) % to that required by libsvm and write the results (converted % pattern data) to the file. % nclass: number of classes. % outFname: output (ascii) file name. % An example: % Traditional format (nclass = 3): %----------------------------------- % Features | Labels %----------------------------------- % 0.101 1.2 0 3.4 4.5 | 1 0 0 % 0 0 3.2 1.9 2.7 | 0 1 0 % 4.5 2.3765 4.6 0 9.3 | 0 0 1 % ... %----------------------------------- % % LIBSVM format %----------------------------------- % Labels | Features %----------------------------------- % 1 1:0.101 2:1.2 4:3.4 5:4.5 % 2 3:3.2 4:1.9 5:2.7 % 3 1:4.5 2:2.3765 3:4.6 5:9.3 % ... %----------------------------------- % % Note that "0" entries in the feature field will not % indexed and listed. % % by Dan Li, 8/16/01 % convert the label field % modified by Yu Hen Hu on 10/13/01 % if nclass = 0, it translate into a model file. The first column of X % will be the lagrange multipliers and remain at the first column [npattern, N] = size(X); if nclass > 0, nfeature = N-nclass; else nfeature = N-1; end if ~isempty(outFname) fid = fopen(outFname,'wt'); if fid ~= -1 , % if file open is successful for i = 1:npattern if nclass > 0, Z = num2str(X(i,end-nclass+1:end)*(1:nclass)'); for j = 1:nfeature if X(i,j)~=0 Z = [Z ' ' num2str(j) ':' num2str(X(i,j))]; end end elseif nclass==0, Z = num2str(X(i,1)); for j = 2:N, if X(i,j)~=0 Z = [Z ' ' num2str(j) ':' num2str(X(i,j))]; end end end fprintf(fid,'%s\n',Z); end fclose(fid); else % report error error(['cannot open ' outFname '!']) end % if end