120 likes | 230 Views
Computer Simulation Lab. “Lecture 11”. Electrical and Computer Engineering Department SUNY – New Paltz. Importing and exporting data. Objectives • the load and save commands; • low-level file I/O functions. Save Command. SAVE Save workspace variables to disk.
E N D
Computer Simulation Lab “Lecture 11” Electrical and Computer Engineering Department SUNY – New Paltz SUNY-New Paltz
Importing and exporting data Objectives • the load and save commands; • low-level file I/O functions. SUNY-New Paltz
Save Command SAVE Save workspace variables to disk SAVE FILENAME saves all variables to binary “filename.mat" SAVE FILENAME X Y Z saves X, Y, and Z SAVE ... -ASCII SUNY-New Paltz
Examples A =[1 2 3 ; 4 5 6] save myData A View myData.mat with a text editor save myData -ascii SUNY-New Paltz
Load Command load myData load myData.txt A=load(‘myData.txt’) SUNY-New Paltz
Low-level file I/O functions SUNY-New Paltz
Low-level file I/O functions fid = fopen(’marks.bin’, ’w’) fwrite(fid, name) File Handle fread(fid, 78, ’float’); fclose(fid) SUNY-New Paltz
Low-level file I/O functions Pointer Update fid = fopen(’marks.bin’, ’w’) fwrite(fid, name) Open for Write Variable Name SUNY-New Paltz
Low-level file I/O functions Pointer Update fid = fopen(’marks.bin’, ’r’) A=fread(fid, 16, ‘float’) Variable Name Open for Read Variable Size&Type SUNY-New Paltz
Examples 1- Create a binary file named “odd.bin” that contains all the odd numbers between 1 and 99. Examine the file by text editor. 2- Open the binary file and read its contents into an array named OddNums. 3- Append the even numbers between 2 and 100 to the above file. Examine the file by text editor. SUNY-New Paltz
MATLAB Code fid=fopen('test1.bin','a') x=[2:2:100]; fwrite(fid,x) fclose(fid); fid=fopen('test1.bin','r') y = fread(fid) fclose(fid); fid=fopen('test1.bin','w') x=[1:2:100]; fwrite(fid,x) fclose(fid); fid=fopen('test1.bin','r') y = fread(fid) fclose(fid); SUNY-New Paltz
Example Create a text file named ‘ASCII.TXT’ that contains all the ASCII characters between 0 and 255. Use a text editor to examine the file. fid=fopen('ASCII.TXT','w') x=[1:255]; fwrite(fid,char(x)) fclose(fid); SUNY-New Paltz