如何将 SPSS 数据文件直接传输到 Matlab 矩阵,反之亦然?



有谁知道在 Matlab 矩阵中传输 SPSS .sav或任何其他 SPSS 数据文件的最佳方法是什么,反之亦然?(也许直接)

我发现的唯一方法是:

  1. 将 SPSS 数据集另存为 Excel 文件。
  2. 在 Matlab 工作区中打开 excel 文件。
  3. 通过以下方式读取 Matlab-matrix (A) 中的 excel 文件:A = readxls('filename.xlsx')

我正在寻找一种直接的方法,可以在 Matlab 矩阵中引入/转换 SPSS 数字数据集,而不是相反。

从 Matlab 到 SPSS,我已经将我的 Matlab-matrix 导出到一个.txt文件中并打开了它 SPSS。

我找到了PSPP*的解决方案,这可能对SPSS也有好处。这个想法很简单 - 按照您在问题中描述的内容进行操作,但以自动化的方式进行。

首先为 SPSS编写一个脚本文件(以下内容适用于 PSPP,但应该与 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.

如果您想要数值而不是标签,请写CELLS=VALUES

保存此文件(假设它称为spss2csv.sps)。

在 Matlab 中,编写以下内容:

sps_file_name = 'full_pathspss2csv.sps';
% replace the path below with the path for SPSS:
command = ['"C:Program FilesPSPPbinpspp.exe" ' sps_file_name];
system(command)

这将生成一个.csv文件,您可以通过xlsread或使用导入工具将其导入到 Matlab:

uiimport(your_resulted_CSV_file_with_full_path.csv)

此工具允许您导入混合数据,并生成脚本,以便下次可以自动完成。

对于相反的方向(Matlab到SPSS),请查看这些提交给File Exchange的内容:

  1. 将数据导出到 SPSS。
  2. 保存4SPSS。

*PSPP是免费的,运行速度非常快,所以如果你不能在SPSS中实现这一点,只需下载它。


如果你安装了PSPP,你可以在Matlab中使用这个函数,而不需要离开Matlab:

function import_sav(sav_file,labels)
% Opens the import tool for importins a sav file
% 'sav_file' is the name of the SPSSPSPP 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:UsersEyalDropboxMATLABatidresult.sav';
csv_file = [p '' csv_file '.csv'];
fid = fopen(sps_file,'w');
fprintf(fid,'GET FILE =  ''%s''n',sav_file);
fprintf(fid,'save translaten');
fprintf(fid,'tt/outfile = ''%s''n',csv_file);
fprintf(fid,'tt/type = CSVn');
fprintf(fid,'tt/REPLACEn');
fprintf(fid,'tt/FIELDNAMESn');
if labels
fprintf(fid,'tt/CELLS=LABELS.n');
else
fprintf(fid,'tt/CELLS=VALUES.n');
end
fclose(fid);
command = ['"C:Program FilesPSPPbinpspp.exe" ' sps_file];
system(command)
uiimport(csv_file)
end

这将自动打开您在调用函数时输入的.sav文件的数据导入工具:import_sav('my_file.sav',1)

如果 Matlab 支持 ODBC 进行输入,并且您可以获取 SPSS ODBC 驱动程序,则可以直接针对 SAV 文件发出 ODBC 查询。

最新更新