MATLAB - Data Processing 기초

[MATLAB Data Processing 기초 1] Excel file - 불러오기, 저장하기( readtable(), writetable() )

toyprojects 2023. 8. 9. 21:31

 

 

Excel 프로그램은 공학이던 비전문가 이던 분야를 막론하고 접근하기 쉽고, 데이터의 수집, 편집이 직관적이며 

공유등이 수월한 장점 때문에 빈번하게 사용되고 있습니다. 하지만 데이터의 크기와 복잡성이 높으면 일일이

수동으로 작업을 처리하기 어렵고 시간적으로 효율성이 떨어질 수가 있습니다. 따라서 MATLAB 등 프로그래밍을

통한 Excel 파일의 데이터 처리를 자동화 할수 있다면 작업시간이 단축되고 업무의 효율을 높일 수 있습니다.

본 포스트에서는 Windows 환경에서 Excel 파일의 데이터를 간단하게 다뤄보고자 합니다.

MATLAB은 ActiveX 기술로써 Excel과 커뮤니케이션을 하기 때문에 Excel 대부분의 기능을 활용할 수 있지만 (출처 1,

MathWorks Support Team의 공식 답변 참조), Mac과 Linux 환경에서는 제한사항이 있습니다.

따라서 MATLAB의 File Exchange 등에서 써드파티 파일을 찾아 - "excel mac", "excel linux" 등의 키워드 사용 -

사용하시기 바랍니다. 

 

데이터를 Excel file로 저장하기 위해 writetable( ) 명령어를 사용하지만 MATLAB 2019a 버전 부터는 writecell( )

명령어 또한 지원하고 있습니다. 단, 기존에 주로 사용되던 xlswrite( ) 는 권장하지 않습니다.

수월한 절차를 위해 데이터 어레이(array) 또는 매트릭스(matrix)를 table 형식의 데이터로 변환하여 writetable( )의

입력 파라메터로써 프로그래밍 하였습니다.

 

4개의 그룹(GroupA 부터 GroupD)이 있으며 각 그룹에는 15명의 키(160cm 부터 200cm 까지)가 기록된 

데이터 매트릭스(matrix)가 있습니다. GroupA 부터 GroupC 까지 각 그룹의 키는 랜덤으로써 지정되어 있으며

GroupD의 키는 '0' 으로 초기화 되어 있습니다. 

프로그램의 목적은 1) 데이터 매트릭스(matrix)를 excel file 로 저장하고, 2) 같은 파일을 불러오기 하여, 

3) GroupD 15명의 키 또한 160cm - 200cm 범위의 랜덤값으로써 지정하여, 4) 각 그룹의 평균과 표준편차(standard

deviation)을 구하는 것입니다.

 

 

1) 데이터 매트릭스(matrix)를 excel file 로 저장하기

 

 

예를들어, 위의 15x4 데이터 매트릭스는 다음의 코드를 이용하여 랜덤값으로 지정하였습니다.

 

num_ppl = 15;                       % how many data 
num_group = 4;                      % how many groups
height = zeros(num_ppl,num_group);  % data initialization

rnd_height = 160 + (200-160).*rand(num_ppl,num_group-1);    % 160-200cm height 
height(:,1:num_group-1) = rnd_height(:,1:num_group-1);      % record data of the first 3 groups

 

rand( ) 명령어로써 랜덤값을 생성 하였으므로 매번 실행때마다 변경될 것입니다. 그리고 키의 범위가 160cm - 200cm로

지정되었으므로 rand( )이 생성한 0과 1사이 랜덤값을 지정된 범위에 맞추기 위한 코드를 갖춰야 합니다. 

데이터 매트릭스의 GroupD는 초기값 '0' 으로 남아있습니다.

이제 이 데이터 매트릭스를 'height_data.xlsx' 라는 excel file로 저장하겠습니다.

 

file_name = 'height_data.xlsx';
var_names = {'GroupA','GroupB','GroupC','GroupD'};           % variable names

tb_height = array2table(height,'VariableNames',var_names);   % convert array to table 
writetable(tb_height,file_name,'Sheet',1,'Range','B2:E18');  % save the data

 

 

데이터 매트릭스는 array2table( ) 으로 간단하게 table 형태로 변환되었습니다. 

table 타입 데이터의 각 행의 제목, 예를들어 GroupA, GroupB 등을 'Variable Names' 라고 부르며, array2table( ) 의

옵션 파라메터 'VariableNames' 부분에 원하는 이름들을 명시합니다. 그 외에도 다양한 옵션들이 존재하므로 

MATLAB 도움말에서 반드시 참조하시길 바랍니다. 구글 검색에서 "matlab table" 키워드로 검색하셔도 됩니다.

 

table 형태로 변환된 데이터는 writetable( ) 의 입력 파라메터로써 손쉽게 excel file로 저장되었습니다.

기본적으로 저장할 데이터와 파일이름 만으로 excel file 생성이 가능하며, 위의 코드에서는 첫번째 excel sheet에

B2:E18 데이터 범위를 직접 지정하였습니다. 마찬가지로 MATLAB 도움말에서 "writetable" 을 참조하시기 바랍니다.

 

 

2) Excel file 불러오기

 

excel file 저장하기와 비슷하게 readtable( ) 명령어 로써 excel file의 데이터를 table 형식으로 불러올 수 있습니다.

 

file_name = 'height_data.xlsx';
read_tb_height = readtable(file_name);                      % load the data

read_tb_height.Variables

 

위 코드의 'read_tb_height' 는 table 타입의 데이터 이므로 실수 데이터만을 지정하기 위해 첨자문인 '.Variables' 를

반드시 사용하여야 합니다.

 

 

 

3) 데이터 편집

 

GroupD의 데이터는 아직 '0' 으로 초기화 되어 있고 위에서와 같은 방법으로 160cm - 200cm 범위의 랜덤값을

생성합니다. 이것은 15개의 실수값 벡터(vector) 이므로 table 형식의 read_tb_height에 삽입하기 위해 

Variable Names 중 GroupD를 첨자로 선택합니다. 

 

마지막으로 각 그룹의 평균과 표준편차(standard deviation)을 구하기 위해 read_tb_height의 실수 데이터만을

가져와야 하므로 '.Variables' 첨자를 사용함으로써 각각 mean( ), std( ) 명령어를 연산할 수 있습니다.

 

 

rnd_height = 160 + (200-160).*rand(num_ppl,1);              % 160-200cm height 
read_tb_height.GroupD = rnd_height;                 
mean_group = mean(read_tb_height.Variables,1);              % mean of height each group
std_group = std(read_tb_height.Variables,1);                % standard deviation of height each group

 

read_tb_height - GroupD 데이터 삽입후

 

mean_group

 

std_group

 

 

마지막으로 본 글에 쓰인 모든 MATLAB 코드는 밑에 표시해 두었습니다.

 

% create random data of three groups and save data into an excel file
file_name = 'height_data.xlsx';
var_names = {'GroupA','GroupB','GroupC','GroupD'};           % variable names

num_ppl = 15;                       % how many data 
num_group = 4;                      % how many groups
height = zeros(num_ppl,num_group);  % data initialization

rnd_height = 160 + (200-160).*rand(num_ppl,num_group-1);    % 160-200cm height 
height(:,1:num_group-1) = rnd_height(:,1:num_group-1);      % record data of the first 3 groups

tb_height = array2table(height,'VariableNames',var_names);  % convert array to table 
writetable(tb_height,file_name,'Sheet',1,'Range','B2:E18'); % save the data

% read the excel file and edit data
read_tb_height = readtable(file_name);                      % load the data

rnd_height = 160 + (200-160).*rand(num_ppl,1);              % 160-200cm height 
read_tb_height.GroupD = rnd_height;                 
mean_group = mean(read_tb_height.Variables,1);              % mean of height each group
std_group = std(read_tb_height.Variables,1);                % standard deviation of height each group

 

 

 

출처 1: https://www.mathworks.com/matlabcentral/answers/94822-are-there-any-examples-that-show-how-to-use-the-activex-automation-interface-to-connect-matlab-to-ex

 

Are there any examples that show how to use the ActiveX automation ...

I am trying to control Excel from MATLAB using ActiveX. I would like some examples that show how to use the ActiveX automation interface from Excel to do this.

www.mathworks.com