Matlab input format

我只是一个虾纸丫 提交于 2019-12-02 09:33:31

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!