Matlab input format

你说的曾经没有我的故事 提交于 2019-12-31 07:06:24

问题


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?


回答1:


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

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