0

我正在努力解决一个问题,想要一个简单的方法。我有一大堆数据,其中有一些向量值(1.02 1.23 3.32)格式。我希望它以表格形式显示为 1.02 1.23 3.32。这里的问题是有两种类型的分隔符'('和')'。

任何人都可以帮助为此编写代码吗?我有这样的事情:

 filename = 'U.dat';
delimiterIn = '(';
headerlinesIn = 0;
A = textscan(filename,delimiterIn,headerlinesIn);

但有一件事是它只有一个分隔符“(”,它也不起作用。

尼尚

4

1 回答 1

0

如果您的文本文件如下所示:

(1 2 3) (4 5 6)
(7 8 9) (10 11 12)

您可以将其作为字符串读取并将其转换为向量元胞数组,如下所示:

% read in file
clear all
filename = 'delim.txt';
fid  = fopen(filename); %opens file for reading
tline = fgets(fid); %reads in a line
index = 1; 
 %reads in all lines until the end of the file is reached
while ischar(tline)
    data{index} = tline;     
    tline = fgets(fid);         
    index = index + 1;
end
fclose(fid); %close file

% convert strings to a cell array of vectors
rowIndex = 1;
colIndex = 1;
outData = {};
innerStr = [];

for aCell = data  % for each entry in data
    sline = aCell{1,1}; 
    for c = sline % for each charecter in the line
        if strcmp(c, '(')
            innerStr = [];
        elseif strcmp(c, ')')
            outData{rowIndex,colIndex} = num2str(innerStr);
            colIndex = colIndex + 1;
        else
            innerStr = [innerStr, c];
        end
    end

     rowIndex = rowIndex + 1;
     colIndex = 1;
end

outData  
于 2013-03-21T16:01:20.307 回答