我有以下格式的包含数据的输入文件。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中使用此输入格式?
我有以下格式的包含数据的输入文件。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中使用此输入格式?
由于您的文件中包含可能被认为是结构化(或“格式化”,如果用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
非常感谢。那很完美! –
@ Md.AbidHasan - [如何接受答案的工作?](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – rayryeng
对不起,我是新来的堆栈溢出。不知道@rayryeng –
你在'##### /%c'行之间总是有4行数据? –
是的,它始终是一个4x4矩阵 –