Does anyone know what is the best way to transfer an SPSS .sav or any other SPSS Data file in a Matlab matrix and vice versa? (maybe directly)
The only way I found was this:
A = readxls('filename.xlsx')
I am looking for a direct way to bring/convert SPSS numeric dataset in a Matlab matrix and vice versus.
From Matlab to SPSS I have exported my Matlab-matrix in a .txt file and opened it SPSS.
I found a solution for PSPP*, that might be good for SPSS as well. The idea is simple - do what you describe in the question, but in an automated manner.
Start by writing a script file for SPSS (the following is for PSPP, but should be very similar to SPSS):
GET FILE = 'your_SPSS_file_with_full_path.sav'
save translate
/outfile = 'your_resulted_CSV_file_with_full_path.csv'
/type = CSV
/REPLACE
/FIELDNAMES
/CELLS=LABELS.
write CELLS=VALUES
if you want the numeric value and not the lables.
Save this file (let's say it's called spss2csv.sps).
In Matlab, write the following:
sps_file_name = 'full_path\spss2csv.sps';
% replace the path below with the path for SPSS:
command = ['"C:\Program Files\PSPP\bin\pspp.exe" ' sps_file_name];
system(command)
This will generate a .csv file, that you can import to Matlab either by xlsread
or by using the import tool:
uiimport(your_resulted_CSV_file_with_full_path.csv)
This tool lets you import mixed data, and generate a script so that could be done automatically the next time.
For the opposite direction (Matlab to SPSS) take a look at these submissions to File Exchange:
*PSPP is free and works extremely fast, so if you can't implement this in SPSS just download it.
Here is a function that you can use in Matlab if you install PSPP, without getting out of Matlab at all:
function import_sav(sav_file,labels)
% Opens the import tool for importins a sav file
% 'sav_file' is the name of the SPSS\PSPP file to import
% 'labels' is a logical that if true then the file is imported using the
% labels and not the numeric values. Default is TRUE.
if nargin<2
labels = true;
end
[p,csv_file] = fileparts(sav_file);
if isempty(p), p = cd; end
sps_file = [p '\convert2csv.sps'];
% sav_file = 'C:\Users\Eyal\Dropbox\MATLAB\atid\result.sav';
csv_file = [p '\' csv_file '.csv'];
fid = fopen(sps_file,'w');
fprintf(fid,'GET FILE = ''%s''\n',sav_file);
fprintf(fid,'save translate\n');
fprintf(fid,'\t\t/outfile = ''%s''\n',csv_file);
fprintf(fid,'\t\t/type = CSV\n');
fprintf(fid,'\t\t/REPLACE\n');
fprintf(fid,'\t\t/FIELDNAMES\n');
if labels
fprintf(fid,'\t\t/CELLS=LABELS.\n');
else
fprintf(fid,'\t\t/CELLS=VALUES.\n');
end
fclose(fid);
command = ['"C:\Program Files\PSPP\bin\pspp.exe" ' sps_file];
system(command)
uiimport(csv_file)
end
This will automatically open the data import tool for that .sav file that you enter when calling the function: import_sav('my_file.sav',1)
.