Io 如何读取带八度的字符串/数字分隔文件?

Io 如何读取带八度的字符串/数字分隔文件?,io,octave,Io,Octave,我正在尝试使用八度音阶读取包含数字和字符串的文本文件。文件格式如下所示: A B C a 10 100 B202000 C303000 d 40 400 e 50 500 但分隔符可以是空格、制表符、逗号或分号。如果分隔符为空格/制表符,则textread函数可以正常工作: [A,B,C]=textread('test.dat','%s%d%d','headerlines',1) 但是,如果分隔符是逗号/分号,则它不起作用。我尝试使用dklmread: dlmread('test.dat',';

我正在尝试使用八度音阶读取包含数字和字符串的文本文件。文件格式如下所示:

A B C
a 10 100
B202000
C303000
d 40 400
e 50 500
但分隔符可以是空格、制表符、逗号或分号。如果分隔符为空格/制表符,则textread函数可以正常工作:

[A,B,C]=textread('test.dat','%s%d%d','headerlines',1)

但是,如果分隔符是逗号/分号,则它不起作用。我尝试使用dklmread:

dlmread('test.dat',';',1,0)

但它不起作用,因为第一列是字符串。
基本上,对于textread,我不能指定分隔符;对于dlmread,我不能指定第一列的格式。至少在八度音阶中,这些函数的版本不是这样的。以前有人遇到过这个问题吗?

目前我在八度音阶中找不到一个简单的方法来解决这个问题。您可以使用
fopen()
在文件中循环并手动提取数据。我编写了一个函数,可以对任意数据执行此操作:

function varargout = coltextread(fname, delim)

    % Initialize the variable output argument
    varargout = cell(nargout, 1);

    % Initialize elements of the cell array to nested cell arrays
    % This syntax is due to {:} producing a comma-separated 
    [varargout{:}] = deal(cell());

    fid = fopen(fname, 'r');

    while true
        % Get the current line
        ln = fgetl(fid);

        % Stop if EOF
        if ln == -1
            break;
        endif

        % Split the line string into components and parse numbers
        elems = strsplit(ln, delim);
        nums = str2double(elems);

        nans = isnan(nums);

        % Special case of all strings (header line)
        if all(nans)
            continue;
        endif

        % Find the indices of the NaNs 
        % (i.e. the indices of the strings in the original data)
        idxnans = find(nans);

        % Assign each corresponding element in the current line
        % into the corresponding cell array of varargout
        for i = 1:nargout
            % Detect if the current index is a string or a num
            if any(ismember(idxnans, i))
                varargout{i}{end+1} = elems{i};
            else
                varargout{i}{end+1} = nums(i);
            endif
        endfor
    endwhile

endfunction
它接受两个参数:文件名和分隔符。该函数由指定的返回变量数控制,例如,
[ab C]=coltextread('data.txt',';')
将尝试从文件中的每一行解析三个不同的数据元素,而
A=coltextread('data.txt',';')将只解析第一个元素。如果没有给出返回变量,那么函数将不会返回任何内容

该函数忽略包含所有字符串的行(例如“A B C”标题)。如果您需要所有内容,只需删除
if all(nans).
部分即可

默认情况下,“列”作为单元格数组返回,尽管这些数组中的数字实际上是转换后的数字,而不是字符串。如果您知道单元格数组只包含数字,则可以轻松地将其转换为列向量:
cell2mat(a)

允许您指定分隔符——它接受的属性参数。以下代码适用于我:

[A,B,C] = textread( 'test.dat', '%s %d %d' ,'delimiter' , ',' ,1 )