【问题标题】:Matlab - preprocess CSV fileMatlab - 预处理CSV文件
【发布时间】:2013-11-27 18:57:11
【问题描述】:

我有一个类似于以下格式的 CSV 文件:

title1 
index   columnA1  columnA2  columnA3
1       2         3         6
2       23        23        1
3       2         3         45
4       2         2         101
title2 
index   columnB1  columnB2  columnB3
1       23        53        6
2       22        13        1
3       5         4         43
4       8         6         102

我想构建一个函数readCustomCSV,它接收一个如下图所示格式的CSV文件和一个行索引i,并返回一个输出文件(比如i = 3),内容如下:

title1 
index   columnA1  columnA2  columnA3
3       2         3         45
title2 
index   columnB1  columnB2  columnB3
3       5         4         43

您知道如何使用csvread 函数来获得此类功能吗?

让我感到困惑的是有 2 种类型部分。我正在考虑将整个内容用作字符串,然后将其拆分为 2 个 .csv 文件,然后读取相应的行。

【问题讨论】:

  • 请注意,csvread 要求 CSV 文件包含纯数字数据。看看this question。最高且被接受的答案为您提供了一个函数read_mixed_csv,它可以让您将整个 CSV 文件作为单元矩阵导入。

标签: matlab csv


【解决方案1】:

尝试使用此功能: 我假设所有表都有相同数量的列/行。代码绝对可以缩短/改进/扩展;)

function multi_table_csvread (row_index)
filename_INPUT = 'multi_table.csv' ;
filename_OUTPUT = 'selected_row.csv' ;
fIN = fopen(filename_INPUT,'r');
nextLine = fgetl(fIN);
tableIndex = 0;
tableLine = 0;
csvTable = [];
% start reading the csv file, line by line
while nextLine ~= -1
    lineStr =  strtrim(strsplit(nextLine,',')) ;
    % remove empty cells 
    lineStr(cellfun('isempty',lineStr)) = [] ; 
    tableLine = tableLine + 1 ;
    % if 1 element start new table
    if numel(lineStr) == 1
        tableIndex = tableIndex + 1;
        tableLine = 1;
        csvTable{tableIndex,tableLine} = lineStr ;
    else
        lineStr = add_comas(lineStr) ;
        csvTable{tableIndex,tableLine} = lineStr ;
    end
    nextLine = fgetl(fIN);
end
fclose(fIN);
fOUT = fopen(filename_OUTPUT,'w');
if row_index > size(csvTable,2) -2
    error('The row index exceeds the maximum number of rows!')
end
for k = 1 : size(csvTable,1)
    title = csvTable{k,1};
    columnHeaders = csvTable{k,2};
    selected_row = csvTable{k,row_index+2};
    fprintf(fOUT,'%s\n',title{:});
    fprintf(fOUT,'%s',columnHeaders{:});
    fprintf(fOUT,'\n');
    fprintf(fOUT,'%s',selected_row{:});
    fprintf(fOUT,'\n');
end
fclose(fOUT);

function line_with_comas = add_comas(this_line)

for ii = 1 : length(this_line)-1
    this_line{ii} = strcat(this_line{ii},',') ;
end
line_with_comas = this_line ;

【讨论】:

    猜你喜欢
    • 2014-08-10
    • 2014-08-12
    • 2011-08-07
    • 1970-01-01
    • 2018-10-12
    • 2017-11-09
    • 1970-01-01
    • 2021-01-28
    • 2015-10-05
    相关资源
    最近更新 更多