在matlab中读取数组中的文件

时间:2016-09-13 18:49:26

标签: matlab

1     0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1
2     0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1
3     0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1
4     0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0
5     0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1
6     0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0
7    0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1

我有上面的文本文件。我想在Matlab中阅读这个文件并想存储 数组中的文件内容分为两列。在第一栏中 序列号和另一列16位模式如下

{{1}}

有人能帮助我吗?

1 个答案:

答案 0 :(得分:0)

如果索引的排序方式与1:n(或任何其他已知订单)相同,则可以使用此选项:

fileID = fopen('bin16.txt');
raw = fscanf(fileID,'%s');
fclose(fileID);
colon_ind = strfind(raw,'::');
data = table((1:numel(colon_ind)).',...
    cell(numel(colon_ind),1),...
    'VariableNames',{'Index','Pattern'});
counter = 1;
for k = colon_ind
    data.Pattern(counter,:) = {raw(k+2:k+17)};
    counter = counter+1;
end

得到这个:

data = 
    Index         Pattern      
    _____    __________________
     1       '0000000000000011'
     2       '0000000000000101'
     3       '0000000000001001'
     4       '0000000000000110'
     5       '0000000000010001'
     6       '0000000000001010'
     7       '0000000000000111'
     8       '0000000000010010'
     9       '0000000000001100'
    10       '0000000000001011'
    11       '0000000000100001'
    12       '0000000000010100'

如果没有订购索引列,您可以使用以下内容:

fileID = fopen('bin16b.txt','r');
raw = fscanf(fileID,'%s');
C = textscan(raw,'%s','delimiter','::');
fclose(fileID);
N = (size(C{1},1)-1)/2;
data = table(zeros(N,1),cell(N,1),...
    'VariableNames',{'Index','Pattern'});
data.Index(1) = str2num(C{1}{1,1});
for k = 1:N
    if k>1
        data.Index(k) = str2num(C{1}{k*2-1,:}(17:end));
    end
    data.Pattern(k,:) = {C{1}{k*2+1,:}(1:16)};
end

获取(我输入了一些任意数据):

Index         Pattern      
_____    __________________
54       '0000000000000011'
 6       '0000000000000101'
 3       '0000000000001001'
 4       '0000000000000110'
 5       '0000000000010001'
92       '0000000000001010'
 7       '0000000000000111'
35       '0000000000010010'
 9       '0000000000001100'
10       '0000000000001011'
11       '0000000000100001'
12       '0000000000010100'

修改

如果' ::'在文件中可以删除之前,然后你可以使用:

text = load ('bin16b.txt', '-ascii');
data = table(text(:,1),text(:,2:end),...
    'VariableNames',{'Index','Pattern'});

并获得:

data = 
    Index       Pattern   
    _____    _____________
    54       [1x16 double]
     6       [1x16 double]
     3       [1x16 double]
     4       [1x16 double]
     5       [1x16 double]
    92       [1x16 double]
     7       [1x16 double]
    35       [1x16 double]
     9       [1x16 double]
    10       [1x16 double]
    11       [1x16 double]
    12       [1x16 double]

其中模式列中的每个单元格如下:

>> data.Pattern(1,:)
ans =
  Columns 1 through 14
     0     0     0     0     0     0     0     0     0     0     0     0     0     0
  Columns 15 through 16
     1     1