2016-03-07 99 views
0

我有以下格式的包含數據的輸入文件。Matlab輸入格式

65910/A 
22 9 4 2 
9 10 4 1 
2 5 2 0 
4 1 1 0 
65910/T 
14 7 0 4 
8 4 0 2 
1 2 0 0 
1 1 1 1 
. 
. 
. 

我需要採取的輸入,其中第一線是%d%c利用其間的/和接下來的四線作爲4x4整數矩陣的組合。我需要在矩陣上執行一些工作,然後用標題信息標識它們。

如何在MATLAB中使用此輸入格式?

+0

你在'##### /%c'行之間總是有4行數據? –

+0

是的,它始終是一個4x4矩陣 –

回答

2

由於您的文件中包含可能被認爲是結構化(或「格式化」,如果用MATLAB的條款),你可以使用textscan功能來閱讀其內容的數據。這個函數的主要優點是你不需要指定你的「header + data」結構出現的次數 - 函數只是一直持續下去,直到它到達文件末尾。

給定的輸入文件結構如下(我們稱之爲q35853578.txt):

65910/A 
22 9 4 2 
9 10 4 1 
2 5 2 0 
4 1 1 0 
65910/T 
14 7 0 4 
8 4 0 2 
1 2 0 0 
1 1 1 1 

我們可以寫這樣的事:

function [data,headers] = q35853578(filepath) 
%// Default input 
if nargin < 1 
    filepath = 'q35853578.txt'; 
end 
%// Define constants 
N_ROWS = 4; 
VALS_PER_ROW = 4; 
NEWLINE = '\r\n'; 
%// Read structured file contents 
fid = fopen(filepath); 
headers = textscan(fid,['%u/%c' repmat([NEWLINE repmat('%u',1,VALS_PER_ROW)],1,N_ROWS)]); 
fclose(fid); 
%// Parse contents and prepare outputs 
data = cell2mat(reshape(cellfun(@(x)reshape(x,1,1,[]),headers(3:end),... 
    'UniformOutput',false),VALS_PER_ROW,N_ROWS).'); %' 
headers = headers(1:2); 
%// Output checking 
if nargout < 2 
    warning('Not all outputs assigned, some outputs will not be returned!') 
end 
%// Debug 
clear ans fid N_ROWS NEWLINE VALS_PER_ROW filepath 
keyboard; %// For debugging, delete/comment when done. 

輸出結果是uint32以3D陣列(輸出類別可通過調整輸入textscan進行更改,如formatSpec所允許):

ans(:,:,1) = 

      22   9   4   2 
      9   10   4   1 
      2   5   2   0 
      4   1   1   0 


ans(:,:,2) = 

      14   7   0   4 
      8   4   0   2 
      1   2   0   0 
      1   1   1   1 
+0

非常感謝。那很完美! –

+0

@ Md.AbidHasan - [如何接受答案的工作?](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – rayryeng

+0

對不起,我是新來的堆棧溢出。不知道@rayryeng –