2013-11-14 3 views
0

전처리 CSV 파일 :matlab에 - 나는 하나 다음과 같은 형식의 CSV 파일이

나는 함수를 넣고 그림 형식으로 CSV 파일을 수신 readCustomCSV 및 행 인덱스를 구축하고자
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 

i하고 다음과 같은 내용 (의이 i = 3을 가정 해 봅시다 용)와 출력 파일을 반환

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

당신이 이러한 유형의 기능을 얻기 위해 csvread 함수를 사용하는 방법을 알고 계십니까?

두 가지 유형 섹션이 있다는 것은 혼란 스럽습니다. 모든 것을 문자열로 사용한 다음 2 개의 .csv 파일로 분할 한 다음 해당 줄을 읽었습니다.

+0

참고 csvread'은 CSV 파일이 순수하게 숫자 데이터를 포함해야'있다. [이 질문] (http://stackoverflow.com/questions/4747834/matlab-import-csv-file-with-mixed-data-types)을보십시오. 가장 높고 수용 가능한 대답은 전체 CSV 파일을 셀 행렬로 가져올 수있는 함수'read_mixed_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 ; 
관련 문제