1 / 29

Ch. 5 File Input and Output

Learn how to open, close, write and read files in MATLAB. Understand the difference between binary and text files and exchange data with other programs using CSV files.

Télécharger la présentation

Ch. 5 File Input and Output

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Ch. 5 File Input and Output 5.1 Opening and Closing Files 5.2 Writing Formatted Output to Files 5.3 Reading Formatted Data from Files 5.4 Writing and Reading Binary Files 5.5 Exchange Data with Other Programs -Comma-Separated Values 제5장 파일의 입력과 출력

  2. Objectives (1) MATLAB에서 파일 열고 닫기 (2) 파일에 정보 쓰기 (3) 파일의 정보 읽기 (4) Binary와 Text 파일의 차이 이해하기 (5) CSV(comma-separated value)파일을 이용해 MATLAB과 다른 프로그램 사이의 데이터 교환 Ch 5 File input and output

  3. 5.1 Opening and Closing Files fid = fopen('filename','permissions') 파일이 제대로 열리면 3 이상의 값을 반환 • -1 : 없는 파일을 열 경우 / error • 0 : 표준입력 • 1 : 표준출력 • 2 : 표준에러 File Identification, the code of the file Ch 5 File input and output

  4. 파일을 여는 경우 매트랩에서 이용 가능한 허가코드 5.1 Opening and Closing Files Ch 5 File input and output

  5. 5.1 Opening and Closing Files status=fclose(fid) MATLAB을 종료하기 전에 FCLOSE함수를 이용하여 파일을 닫아야 함 작업이 정상적으로 끝나면 0을, 아니면 -1을 반환 Ch 5 File input and output

  6. 5.1 Opening and Closing Files FOPEN 함수로 파일 열기 EDU>>pwd ans = C:\MATLAB\TOOLBOX\LOCAL EDU>>dir . . . EDU>> file_id_1 = fopen(‘test1.txt','r'); EDU>> file_id_1 file_id_1 = -1 EDU>> file_id_1 = fopen(‘test1.txt','w'); EDU>> file_id_1 file_id_1 = 3 Ch 5 File input and output

  7. 5.1 Opening and Closing Files FOPEN 함수로 파일 열기 EDU>> file_id_2 = fopen(‘test2.txt','w'); EDU>> file_id_2 file_id_2 = 4 EDU>> file_id_3 = fopen(‘test3.txt','w'); EDU>> file_id_3 file_id_3 = 5 EDU>> file_id_4 = fopen(‘test4.txt','w'); EDU>> file_id_4 file_id_4 = 6 Ch 5 File input and output

  8. 5.1 Opening and Closing Files FCLOSE 함수로 파일 닫기 EDU>>status1=fclose(file_id_1); EDU>>status1 status1 = 0 EDU>> status2=fclose(file_id_2); EDU>> status2 status2 = 0 EDU>> status3=fclose(file_id_3); EDU>> status3 status3 = 0 EDU>> status4=fclose(file_id_4); EDU>> status4 status4 = 0 EDU>> dir . .. test1.txt test2.txt test3.txt test4.txt Ch 5 File input and output

  9. 5.1 Opening and Closing Files 전체 경로명으로 파일 열고 닫기 EDU>>dir c:\transfer . .. EDU>> fid_a = fopen('c:\transfer\xx.txt'.'w') fid_a = 3 EDU>> dir c:\transfer . .. xx.txt EDU>> fclose(fid_a) ans = 0 Ch 5 File input and output

  10. 5.1 Opening and Closing Files 5.1.1 UIGETFILE and UIPUTFILE 파일을 열기 전에 찾을 수 있도록 대화상자를 표시하는 함수 파일을 열지 않고 단지 파일 명과 경로 명을 반환 한다. [filename,pathname] = uigetfile(‘wild card string’,’dialog box title’); [filename,pathname] = uiputfile(‘wild card string’,’dialog box title’); EDU>>[fn , pn]=uigetfile(‘*.*’,’Specify a File Name’) fn = TERMINAL.M pn = D:\MATLAB\TOOLBOX\LOCAL\TERMINAL.M fn = 0 pn = 0 Ch 5 File input and output

  11. 5.1 Opening and Closing Files 5.1.1 UIGETFILE and UIPUTFILE - 존재하지않는 파일을 uigetfile 함수로 시도할 경우 - EDU>>[fn,pn]=uigetfile('*.*','Specify Another File Name') fn = 0 pn = 0 Ch 5 File input and output

  12. 5.1 Opening and Closing Files 5.1.1 UIGETFILE and UIPUTFILE EDU>> [fn,pn]=uiputfile('*.*','Specify a New File Name') EDU>>fid_c=fopen([pn,fn], 'w') fid_c = 4 EDU>> fclose(fid_b) ans = 0 EDU>> fclose(fid_c) ans = 0 fn = newfile.abc pn = C:\MATLABR11\toolbox\local\ Ch 5 File input and output

  13. 5.2 Writing Formatted Output to Files EDU>> fprintf(fid1,'This is text sent to the file indicated by fid1.\n'); EDU>> fprintf(fid1,'We will generate a few lines.\n'); EDU>> fprintf(fid1,'The value of fid1 is %g\n',fid1); EDU>> EDU>> fprintf(fid2,'Send this stuff to file indicated by fid2.\n'); EDU>> fprintf(fid2,'We will generate a few lines in this file as well.\n'); EDU>> fprintf(fid2,'The value of fid2 is %g\n',fid2); EDU>> EDU>> fprintf(fid3,'Lastly, we will send this stuff to file indicated by fid3.\n'); EDU>> fprintf(fid3,'We will generate s few lines in this file too.\n'); EDU>> fprintf(fid3,'The values of fid3 is %g\n',fid3); EDU>> EDU>> fclose(fid1); EDU>> fclose(fid2); EDU>> fclose(fid3); EDU>> Ch 5 File input and output

  14. 5.2 Writing Formatted Output to Files Ch 5 File input and output

  15. Frist_name—A text string of 20 characters Last_name—A text string of 20 characters Address—A text string of 30 characters City—A text string of 20 characters State—A text string of 2 characters Zipcode—A 5-digit integer Zip_p4—A 4-digit integer 5.3 Reading Formatted Data from Files Address book 예) 20인의 주소록인 경우, 각 배열 변수는 20 줄 5번째 인물의 정보 First_name(5,:), Last_name(5,:)….Zipcode(5),Zip_p4(5) Ch 5 File input and output

  16. 5.3 Reading Formatted Data from Files 데이터 입력 % 12345678901234567890 12345678901234567890 12345678901234567890 First_name=['Marc ';'Beth ';'David '] Last_name= ['Smith ';'Prudhome ';'Zimmerman '] City= ['Flagstaff ';'Los Angeles ';'Boston '] % 123456789012345678901234567890 Address= ['2070 S.Del Mar Dr. '; 'P.O Box 12388 '; '112 Thunderbird Av '] State= ['AZ';'CA';'MA'] Zipcode=[86003;96543;02765] Zip_p4=[5679;5393;1209] 데어터 자수가 정해진 문자수 보다 적을 땐 빈칸을 채워야 함 예) 두 번째 인물에 대한 정보 출력 EDU>>fprintf('%s %s\n%s\n%s %s \n%5.0f-%4.0f\n',First_name(2,:), Last_name(2,:),Address(2,:),City(2,:),State(2,:),Zipcode(2),Zip_p4(2)); Beth Prudhome P.O Box 12388 Los Angeles CA 96543-5393 EDU>> Ch 5 File input and output

  17. 5.3 Reading Formatted Data from Files Program 5-1 Write information to the address book %This is file write_ text_ file.m % fid_a=fopen('Address book.txt','a'); forI= 1 : length(Zipcode) fprintf(fid_a,'%20s,%20s,%30s,',First_name(I,:),Last_name(I,:),Address(I,:)); fprintf(fid_a, [City(I,:),',', State(I,:),',']); % to form a single string using concatenation fprintf(fid_a, '%5.0f,%4.0f\n', Zipcode(I), Zip_p4(I)); end fclose(fid_a); EDU>>City= ['Flagstaff ‘ ; 'Los Angeles ‘ ; 'Boston ']; EDU>>State= ['AZ‘ ; 'CA‘ ; 'MA']; EDU>> [City(2,:), ',‘ , State(2,:), ','] ans = Los Angeles ,CA, Ch 5 File input and output

  18. 5.3 Reading Formatted Data from Files Program 5-1 Write information to the address book %This is file write_ text_ file.m % fid_a=fopen('Address book.txt','a'); forI= 1 : length(Zipcode) fprintf(fid_a,'%20s,%20s,%30s,',First_name(I,:),Last_name(I,:),Address(I,:)); fprintf(fid_a, [City(I,:),',', State(I,:),',']); % to form a single string using concatenation fprintf(fid_a, '%5.0f,%4.0f\n', Zipcode(I), Zip_p4(I)); end fclose(fid_a); Ch 5 File input and output

  19. 5.3 Reading Formatted Data from Files Program 5-2 Read the address book %This is file read_ text_ file.m % fid_x=fopen('Address book.txt','r'); First_name=[ ]; Last_name=[ ]; Address=[ ]; City=[ ]; State=[ ]; Zipcode=[ ]; Zip_p4=[ ]; while ~feof(fid_x) str=fscanf(fid_x, '%20c',1); Fist_name=[Frist_name;str]; comma=fscanf(fid_x,'%1c',1); str=fscanf(fid_x, '%20c',1); Last_name=[Last_name;str]; comma=fscanf(fid_x,'%1c',1); str=fscanf(fid_x, '%30c',1); Address=[Address;str]; comma=fscanf(fid_x,'%1c',1); str=fscanf(fid_x, '%20c',1); City=[City;str]; comma=fscanf(fid_x,'%1c',1); Test for end-of-file 파일의 끝에 있는지를 점검 %s는 space를 무시하므로 1 -> 원소 1개(문자열1개) fscanf(fid, format, size) Ch 5 File input and output

  20. 5.3 Reading Formatted Data from Files Program 5-2 Read the address book (Cont’d) while ~feof(fid_x) str=fscanf(fid_x, '%20c',1); Fist_name=[Frist_name;str]; comma=fscanf(fid_x,'%1c',1); str=fscanf(fid_x, '%20c',1); Last_name=[Last_name;str]; comma=fscanf(fid_x,'%1c',1); str=fscanf(fid_x, '%30c',1); Address=[Address;str]; comma=fscanf(fid_x,'%1c',1); str=fscanf(fid_x, '%20c',1); City=[City;str]; comma=fscanf(fid_x,'%1c',1); str=fscanf(fid_x, '%2c',1); State=[State;str]; comma=fscanf(fid_x,'%1c',1); num=fscanf(fid_x, '%5d',1); Zipcode=[Zopcode;num]; comma=fscanf(fid_x,'%1c',1); num=fscanf(fid_x, '%4d',1); Zip_p4=[Zip_p4;num]; end_of_line=fscanf(fid_x,'%1c',1); end fclose(fid_x); 줄끝문자(end-of-line character,\n)를 반드시 읽어야 함 매트랩 프로그램(예 prog 5-3) *.txt 파일을 만든 경우 %1c ‘메모장’으로 만든 파일인 경우 %2c를 해 주어야 함 Ch 5 File input and output

  21. 5.4 Writing and Reading Binary Files FWRITE : ASCII text 형을 Binary 로 쓰는 함수 count=fwrite(FID, A , ‘precision’ ) 바르게 기록 된 요소의 수 precision • ‘char’ – 8-bit character • ‘short’ – 16-bit 정수 (-215 ~ 215 -1) • ‘long’ – 32-bit 정수 (-231 ~ 231 -1) • ‘float’ – single –precision 실수 • ‘double’ – double –precision 실수 Ch 5 File input and output

  22. 5.4 Writing and Reading Binary Files EDU>> fid_bin=fopen('bin_file.abc','w'); EDU>> AA=magic(5) AA = 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9 EDU>> B=rand(7,4) B = 0.9501 0.0185 0.1763 0.3529 0.2311 0.8214 0.4057 0.8132 0.6068 0.4447 0.9355 0.0099 0.4860 0.6154 0.9169 0.1389 0.8913 0.7919 0.4103 0.2028 0.7621 0.9218 0.8936 0.1987 0.4565 0.7382 0.0579 0.6038 EDU>> C=27 C = 27 EDU>> k=‘This is a test’ k = This is a test EDU>> d=pi d = 3.1416 EDU>>fwrite(fid_bin,AA,'double') ans = 25 EDU>>fwrite(fid_bin,B,'double') ans = 28 EDU>>fwrite(fid_bin,C,'short') ans = 1 EDU>>fwrite(fid_bin,k,'char') ans = 14 EDU>>fwrite(fid_bin,d,'double') ans = 1 EDU>>fclose(fid_bin) ans = 0 예 Ch 5 File input and output

  23. 5.4 Writing and Reading Binary Files FREAD : Binary 형에서 ASCII Text로 읽는 함수 [ A , count ] = fread(FID , size , ‘precision’) EDU>>fid_q=fopen('bin_file.abc','r') fid_q = 3 EDU>>[A,count]=fread(fid_q,[5,5],'double') A = 17.1255 24.1255 1.0078 8.0627 15.0627 23.1255 5.0314 7.0314 14.0627 16.1255 4.0314 6.0314 13.0627 20.1255 22.1255 10.0627 12.0627 19.1255 21.1255 3.0157 11.0627 18.1255 25.1255 8.0627 9.0627 count = 25 EDU>>[k,count]=fread(fid_q,[14],'char') k = 84 104 105 115 32 105 115 32 97 32 116 101 115 116 count = 14 문자열은 ASCII 코드 및 열(column)로 읽는다. Ch 5 File input and output setstr(k')로 바꾸어야 문자 및 줄이 된다.

  24. 5.4 Writing and Reading Binary Files Program 5-3 Write a binary file % This is file write_binary_file.m. % fid_a=fopen('Address_book.bin','w'); for I = 1:length(Zipcode) fwrite(fid_a, First_name(I,:), 'char'); fwrite(fid_a, Last_name(I,:), 'char'); fwrite(fid_a, Address(I,:), 'char'); fwrite(fid_a, City(I,:), 'char'); fwrite(fid_a, State(I,:), 'char'); fwrite(fid_a, Zipcode(I), 'long'); fwrite(fid_a, Zip_p4(I), 'short'); end fclose(fid_a); 모니터에는 아무 표시 없음 파일 크기 비교 텍스트 : 325bytes Binary : 294bytes Windows 탐색에서 ‘속성’ 을 확인 해야 함 Ch 5 File input and output

  25. 5.4 Writing and Reading Binary Files Program 5-4 Read a binary file % This is file read_binary_file.m % fid_x=fopen('Address_book.bin','r'); First_name=[ ]; Last_name=[ ]; Address=[ ]; City=[ ]; State=[ ]; Zipcode=[ ]; Zip_p4=[ ]; while ~feof(fid_x) str=fread(fid_x, [20],'char'); First_name = [First_name; setstr(str')] str=fread(fid_x, [20],'char'); Last_name = [Last_name;setstr(str')] str=fread(fid_x, [30],'char'); Address = [Address;setstr(str')] str=fread(fid_x, [20],'char'); City = [City;setstr(str')] str=fread(fid_x, [2],'char'); State = [State;setstr(str')] num=fread(fid_x, 1,'long'); Zipcode=[Zipcode;num] num=fread(fid_x, 1,'short'); Zip_p4=[Zip_p4;num] fprintf('Wait!!!\n') pause end fclose(fid_x); Ch 5 File input and output

  26. 5.5 Exchanging Data with Other Programs (Comma-Separated Values) csvwrite(filename, m) 숫자 (m) 만 CSV로 file에 쓰기 EDU>> a = [ 1 2 3 0 5; 6 7 8 9 10; 11 12 13 14 15; 16 17 18 19 20; 21 22 23 24 25 ] a = 1 2 3 0 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 EDU>> csvwrite(‘xx.csv’, a) Ver 5 이상 Ch 5 File input and output

  27. 5.5 Exchanging Data with Other Programs-Comma-Separated Values Ch 5 File input and output

  28. 5.5 Exchanging Data with Other Programs-Comma-Separated Values Ch 5 File input and output

  29. 5.5 Exchanging Data with Other Programs-Comma-Separated Values d = csvread(‘book3.csv’) Ch 5 File input and output

More Related