2013-06-17 5 views
0

텍스트 파일에서 한 줄을 읽으려고합니다. 이 줄은 textscan을 사용하여 단어로 나뉩니다. textscan의 출력은 구조체 배열 내에 저장됩니다. 각 구조는 한 단어와 위치를 텍스트 파일에 저장합니다.셀 배열의 데이터를 구조체 배열로 복사

Result Time Margin Temperature 

를 그리고 구조의 배열을 원하는 경우 :

예를 들어, 텍스트 파일은 다음과 같이 보일 수 등

headerRow(1).header = Result 
headerRow(1).location = 1 
headerRow(2).header = Time  
headerRow(2).location = 2 

하고 있습니다. 이것은 내 코드입니다 :

headerRow = struct('header', 'location'); 
headerLine = fgets(currentFile) 
temp_cellArray = textscan(headerLine, '%s', ' ') 
for i = 1:size(temp_cellArray), 
    headerRow(i).header = temp_cellArray{i,1} 
    headerRow(i).location = i 
end 

그러나 이것은 전체 4x1 셀만 배열의 첫 번째 요소에 저장합니다. 코드를 원하는대로 작동하게하려면 어떻게해야합니까?

답변

1

라인 temp_cellArray = textscan(headerLine, '%s', ' ')은 셀 배열의 셀 배열을 반환합니다. 셀 배열의 첫 번째 요소를 가져와야합니다. 그러면 셀 배열의 데이터가 생성됩니다.

하기 전에 :

temp_cellArray = 

    {4x1 cell} 

수정 된 코드 :

temp_cellArray = temp_cellArray{1}; 
for ii=1:length(temp_cellArray) 
    headerRow(ii).header = temp_cellArray{ii}; 
    headerRow(ii).location = ii; 
end 

후 :

temp_cellArray = 

    'Result' 
    'Time' 
    'Margin' 
    'Temperature' 


>> headerRow(:).header 

ans = 

Result 


ans = 

Time 


ans = 

Margin 


ans = 

Temperature 

>> headerRow(:).location 

ans = 

    1 


ans = 

    2 


ans = 

    3 


ans = 

    4 
1

나는 그것을 사용하여 한 번에 다음 textscan와 함께 전체 파일을 읽기 위해 더 좋을 것 같아 cell2struct하지만 전자에 대한 자세한 내용을 공유하지 않으면 아무 것도 제안 할 수 없습니다. 입력 파일의 xact 구조. 귀하의 솔루션과 관련하여 다음 수정 방법은 어떻습니까?

headerLine = fgets(currentFile); 
H = textscan(headerLine, '%s', ' ');        %// Headers 
L = num2cell(1:numel(H);           %// Locations 
headerRow = cell2struct([H(:), L(:)], {'header', 'location'}, 2); 
관련 문제