2012-04-03 44 views
1

我有一个包含多个数值矩阵的文件。所有矩阵用换行分隔如显示在下面的例子:负载多martrix文件到Matlab

0,-1,18
1,2,1
2,-1,7
3,-1,12
4, -1,7-

5,-1,23
6,-1,18
7,-1,10
5,-1,23
8,2,9
9, 2,8

15,-1,1
128,-1,7
174,-1,8-
175,-1,0
176,-1,7

我想负载这个文件转换成Matlab工作区,这样每个矩阵将被分配到不同的变量。

Matlab的规定,显然是不适合此类格式的工作简单的负载功能。

如果你有如何加载这样的文件的任何线索,这将是非常有用的。

非常感谢

回答

0

所以文件导入到一个矩阵,并把它分割成你想要的子矩阵。 uiimportdlmread会做的这第一部分,你必须做的第二部分。

如果您的数据集太大以至于无法一次加载它并将其复制到其他变量中,那么您必须使用textscan或类似的函数进行试验才能以块读取文件。

0

这是我的溶液

我的文件变更为以下格式:

n = 3的%数矩阵

在当前矩阵原糖的

R = 3%数目
0的-1 18
2 -1 7


R = 3
3 -1 12
4 -1 7
5 -1 23


R = 5
6 -1 18
7 -1 10
5 -1 23


我实现以下简单函数

 
function data = load_sparse_data(filename) 

% open the file 
fid = fopen(filename); 
% find N (The total number of matrices) 
N = fscanf(fid, 'n=%d\n', 1); 

% read each matrix 
for n = 1:N 
    % skip line 
    fscanf(fid, '\n', 1); 

    % find R, the number of raws 
    R = fscanf(fid, 'r=%d\n', 1); 

    % fscanf fills the array in column order, 
    % so transpose the results 
    data(n).mat = ... 
    fscanf(fid, '%f', [3, R])'; 

    % skip line 
    fscanf(fid, '\n', 1); 
end 

%cloes the file 
fclose(fid);     
1

下面的代码读取所有与TEXTSCAN线,并将它们拆分用空行分离矩阵,然后转换为加倍。

因此,您获得单元阵列out双矩阵作为单个细胞。例如访问第一矩阵使用out{1}等,这比单个变量更好。

%# open file and read all lines 
fid = fopen('test6.txt','rt'); 
temp = textscan(fid, '%s', 'delimiter', '\n'); 
temp = [temp{:}]; 
fclose(fid); 

%# find empty lines 
idxSep = find(cellfun(@isempty, temp)); 
%# separate matrices to different cells 
temp2 = mat2cell(temp, diff([0; idxSep; numel(temp)]), 1); 
%# remove empty lines 
temp2(1:end-1) = cellfun(@(x) x(1:end-1), temp2(1:end-1), 'UniformOutput',0); 

%# convert cell arrays to double 
out = cell(size(temp2)); 
for k = 1:numel(temp2) 
    out{k} = cellfun(@str2num, temp2{k}, 'UniformOutput',0); 
end 
out = cellfun(@cell2mat, out, 'UniformOutput', 0); 

我可能错过了一些东西,使代码更简单。欢迎任何建议。