台湾国立大学郭彦甫Matlab教程笔记(8)文件读写
臺灣國立大學郭彥甫Matlab教程筆記(8)
file access
supported file formats:
1.matlab formatted data .import function:load; export function save
2.text
3.spreadsheet excel .import function xlsread; export function xlswrite
save() and load()
1.save (all) workspace data to a file
code:
執行前兩行代碼
會出現這個保存的文檔
然后我們打開這個文件,發現里面是亂碼。主要是matlab把里面內容壓縮,所以我們看不到原來的東西。
如果想看到原來存儲的內容,就要執行第三行代碼 后面帶有 -ascii,這樣可閱讀
save mydata2.mat -ascii
2.load data stored in a file:
我們先清屏,使用clear;clc
然后執行上面兩行代碼,就會載入進來文件
小練習:如何存儲一個特定的變量,而不是整個工作區?
比如,存儲變量A到一個文件名為varibleA的mat文件中
如果為了可視化,
save('varibleA','A','-ascii');效果:
存儲成txt文檔:
save('varibleA.txt','A','-ascii');效果:
excel file reading :xlsread()
這里有一個excel文件
read from excel spreadsheet
code:
這句話會把excel中的字符和數字分開,也就是這樣讀取進來的是數字
運行結果:
同樣得到這組數據
補充一點: matlab如何讀取excel表格中第二個sheet中的數據?或者第三個sheet中的數據? 今天遇到這個問題,現在回頭補充上。
還是使用xlsread()函數,用法同上,區別是需要指定哪一個sheet,用數字表示,第二個sheet,寫2,第三個sheet寫3,以此類推。位置是在文件名后面。
舉例子:
代碼:
下面代碼是獲取這個excel文件中第三個sheet中的數據,所以數字指定為3。
代碼的解釋:三個參數“”第一個參數是文件名,第二個參數是數字,指定位于哪個sheet,第三個參數是讀取的數據所在位置(位于sheet中),然后得到的數據存放在pingtai這個變量中。
excel file writing :xlswrite()
1.calculate the means平均值 and write into excel spreadsheet
code
M=mean(Score')'; xlswrite('04Score.xlsx',M,1,'E2:E4'); xlswrite( '04Score.xlsx',{'Mean'},1,'E1');解釋:這里mean計算的平均數是每一列的,但是Score中每一位學生都是橫著排列的,是一行。需要轉置一下。mean得到的是一行,再次轉置回來變成一列
運行前兩行得到結果:
大家發現沒有mean的標題,第三行代碼就是給標題xlswrite( ‘04Score.xlsx’,{‘Mean’},1,‘E1’);
結果:
自己的練習:計算標準差,之后寫進第F列
我的思考過程
1.求矩陣的標準差,函數是std()
最后這個變量Var需要轉置,因為excel中的人名是縱向排列的,為了把標準差與之對應,需要再次轉置
2.寫入excel文件
代碼:
解釋:第一個變量:文件名;第二個變量:所要寫入的變量;第三個變量:excel中的哪個sheet;第四個變量:寫入excel中的位置
運行結果:
getting text in excel spreadsheet
1.getting both the text and numbers
指定兩個varible 一個存放成績數字,一個存放表頭
[score header]=xlsread(‘04Score.xlsx’)
作業:
現在有了score 和 header 這兩個變量,我們如何把數字和文字同時用xlswrite寫進去?
完成代碼。
首先我們已經有了score 和header這兩個變量
然后就是需要把這兩個變量寫入到excel中。
代碼:
寫入后的文件,文件名lsz.xlsx
low-level file input/output 低階的文件寫入和輸出
1.read and write file at the byte or character level
2.a file has an ID fid 檔案要有 iD
3.location in the file is specified by a pointer that can be moved around需要有指針
一些指令:
步驟
1 generate x and y
2.open a file
3.write x and y into the file
4.close the file
范例程式:
x=0:pi/10:pi; y=sin(x); fid = fopen('sin.txt','w'); for i=1:11fprintf(fid,'%5.3f %8.4f\n',x(i),y(i)); end fclose(fid); type sin.txt
總結
以上是生活随笔為你收集整理的台湾国立大学郭彦甫Matlab教程笔记(8)文件读写的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 台湾国立大学郭彦甫Matlab教程笔记(
- 下一篇: 台湾国立大学郭彦甫Matlab教程笔记(