2012-04-03 15 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); 

我可能錯過了一些東西,使代碼更簡單。歡迎任何建議。