0

I have input files containing data in the following format.

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
.
.
. 

I need to take the input where the first line is a combination of %d and %c with a / in between and the next four line as a 4x4 integer matrix. I need to perform some work on the matrix and then identify them with the header information.

How can I take this input format in MATLAB?

4

1 回答 1

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.

结果输出是一个 3d 数组uint32(可以通过将输入调整为 来更改输出类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
于 2016-03-07T22:48:54.783 回答