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?
Since your file contains data that may be considered structured (or "formatted", if using MATLAB's terms), you can use the textscan
function to read its contents. The main advantage of this function is that you don't need to specify how many times your "header+data" structure appears - the function just keeps going until it reaches the end of the file.
Given an input file with the following structure (let's call it 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
We can write something like this:
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.
The resulting output is a 3d array of uint32
(the output class can be changed by adjusting the inputs to textscan
, as permitted by 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
来源:https://stackoverflow.com/questions/35853578/matlab-input-format