MATLAB:使用宽度分隔的txt文件进行文本扫描

时间:2015-07-02 11:10:33

标签: matlab width textscan

我尝试使用import QtQuick 2.1 Item { id: box width: 640 height: 480 Rectangle { id: redSquare width: 30; height: 30 anchors.top: parent.top; anchors.left: parent.left; anchors.margins: 10 color: "green" Text { text: "!"; font.pixelSize: 16; anchors.centerIn: parent } } } 函数导入宽度分隔的txt文件。该文件宽度为80个字符,没有分隔符,所需的12列是不同的字符宽度。我试图通过指定字符串的宽度来做到这一点(即12个字符串,每个字符串的不同宽度加起来为80)但是只要有空格(因为缺少某些值),MATLAB会解释这个作为我的分隔符并弄乱了格式。

textscan

我可以使用Excel解决这个问题,但这似乎是一个糟糕的解决方案。有没有办法用MATLAB做这个,可能是一个与data= textscan(fileID, '%5s %7s %1s %1s %1s %17s %12s %12s %10s %5s %6s %3s'); / make textscan不同的函数忘记分隔符并只处理字符串的宽度?

2 个答案:

答案 0 :(得分:1)

您需要将分隔符和空白字符的值更改为空:

format_string = '%5s %7s %1s %1s %1s %17s %12s %12s %10s %5s %6s %3s';
C = textscan(fid, format_string, 'delimiter', '', 'whitespace', '');

这样MATLAB会将每个字符(包括空格)视为有效字符。

答案 1 :(得分:0)

嗯,我遇到过与文本扫描相同的问题。好吧,这是一个很长的路要走(它绝不是最好的解决方案,但它应该工作)

fid=fopen('txtfile.txt','rt'); %//load in file
a=fscanf(fid'%c');       %//scan the thing into chars
fclose(fid);

for r = 0:NumberOfRowsInUrData -1    %//Now the loop... Number of rows in your data can also be calculated by size(a,2)/20 
b(r+1,:) = a(1+20*r:20*(r+1)); %// this will correctly index everything 
end

好处是,现在一切都在矩阵b中,你可以简单地将你的字符索引为string1 = b(:,1:5),它将以一个漂亮的矩阵输出所有内容。

c的缺点是for循环,我认为你应该可以用像cellfun之类的东西来代替。

相关问题