Matlab - 预处理CSV文件

时间:2013-11-14 16:36:13

标签: matlab csv

我有一个类似于以下格式的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个.csv文件,然后读取相应的行。

1 个答案:

答案 0 :(得分: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 ;
相关问题