从文件中加载字符串数组

Loading string array from file

如何从 csvtxt 文件加载 Octave 中的字符串数组?该文件具有如下所示的格式。使用

dlmread("TimeData.csv", ",")

它会产生无用的数据,例如 2019 - 11i

`TIME`
    2019-11-08-13.27.03 +0100
    2019-11-08-13.27.08 +0100
    2019-11-08-13.27.13 +0100
    2019-11-08-13.27.18 +0100
    2019-11-08-13.27.23 +0100

来自 dlmread 的文档(我强调):

Read numeric data from the text file file which uses the delimiter sep between data values.

改为使用 textscan(取决于您的 OS,分隔符可能需要修改):

fid = fopen('TimeData.csv');
C = textscan(fid, '%s', 'Delimiter', '\n')
fclose(fid);

输出:

C =
{
  [1,1] =
  {
    [1,1] = 2019-11-08-13.27.03 +0100
    [2,1] = 2019-11-08-13.27.08 +0100
    [3,1] = 2019-11-08-13.27.13 +0100
    [4,1] = 2019-11-08-13.27.18 +0100
    [5,1] = 2019-11-08-13.27.23 +0100
  }
}

希望对您有所帮助!

类似于 textscan,但它保留空行。

function [textLines] = readFile (file_in_dir)
    if nargin != 1 || isempty(file_in_dir)
        return
    end

    if exist(file_in_dir, "file")
        fid = fopen(file_in_dir, "r");
        data = char(fread(fid));
        fclose(fid);

        if !strcmp(data(end), "\n")
            data = [data ; "\n"];
        end

        data(data == "\r") = [];
        newlines = [0, [1 : rows(data)](data' == "\n")];

        textLines = cell(1, columns(newlines) - 1);
        for i = 1 : columns(newlines) - 1
            textLines{i} = data(newlines(i) + 1 : newlines(i + 1) - 1)';
        end
    else
        textLines = {};
    end
end

不需要丑陋的textscan恶作剧。

只需使用 csv2cell function from the io 包。
我已经用了很多次了,效果很好。