目 錄 javascript
一、GUI新手之——教你讀懂GUI的M文件... 10php
二、GUI程序中改變current directory引發的問題... 15html
三、GUI中h0bject和handles 的區別... 16java
四、handles結構中句柄和對象的關聯問題... 17c++
五、Matlab利用定時器連續顯示圖片的問題... 19git
5-一、GUI中實如今圖片任意位置上標註text. 22web
5-二、使用edit的另一種callback. 22正則表達式
六、MATLAB 如何實現圖像的任意裁減?... 22算法
七、座標軸標註刻度、網格、文字方向... 23express
八、Matlab中對uitable的操做:調節各列寬度,設定某列是可編輯的... 24
九、將在Matlab下編寫的GUI轉成獨立於Matlab平臺的應用程序... 25
十、要將用Matlab語言編寫的函數文件編譯成可獨立執行的*.exe文件... 28
十一、matlab GUI程序轉換成exe可執行文件... 31
十二、gui生成獨立的應用程序的發佈問題... 33
1三、GUI控制simulink模塊及參數的綜合實例!... 34
13-一、在axes顯示圖像後,在圖像上單擊鼠標時,回調函數的定義規則和使用方法... 35
1四、如何在循環中加入waitbar,並在waitbar上添加‘取消’按鈕... 36
1五、在matlab中對信號進行FFT變換... 38
1六、動態顯示figure中曲線的x-y座標值的一個函數... 40
1七、在GUI界面的打開按鈕中,如何對文件進行操做... 42
1八、Matlab不一樣控件之間的數據傳遞問題... 45
1九、在edit box裏輸入相關數據後,直接按回車鍵,不用鼠標點擊pushbutton 就能夠直接執行... 46
19-1 GUI使用editbox輸入數據後如何自動清除數據... 46
20、在GUI中,計算結果怎麼用excel來保存到指定的文件夾中... 47
2一、如何獲得popupmenu選項中最後一個字符串的VALUE值... 49
2二、回調函數互相調用的問題... 49
22-2string和number相互轉換的問題... 50
2三、這樣的功能的pushbutton的callback怎麼寫呀,謝謝了... 50
2四、GUI中axes使用subplot時的清空及axes大小的固定的解決方法... 51
2五、退出GUI時如何把全局變量中的值清空?... 53
2六、從串口接受數據時,如何把波形繪製到指定的座標軸上?... 53
2七、兩個GUI之間如何傳遞數據... 55
28-1 幾個有用的帖子... 57
28-二、GUI之間互相調用和關閉問題... 60
2九、GUI timer定時器... 60
30、如何在循環中加入waitbar. 61
3一、如何連續讀入圖片!!... 62
3二、如何把這次輸入的值保存爲下一次初始化的值... 63
3三、Matlab關於解決自動保存gcf的問題... 63
34-一、在matlab裏面如何讀取excel裏面的數據或者寫入數據... 65
34-二、在excel中連續輸入數據。... 66
3五、Matlab GUI不一樣控件之間的數據傳遞問題... 68
3六、怎麼統計一個十進制數中"0"的個數??求助!... 69
3七、Matlab對listbox裏的條目可否一條條單獨設置回調函數?. 70
3八、鍵盤操做:matlab GUI中如何取得從鍵盤輸入的按鍵的鍵值... 72
3九、GUI如何響應鼠標事件... 73
40、matlab 截圖、圖像處理... 76
4一、MATLAB GUI中利用定時器製做動畫 - [MATLAB]. 84
4二、MATLAB如何從GUI中返回參數 - [MATLAB]. 86
4三、MATLAB 中GUI子程序的參數傳遞 - [MATLAB]. 87
4四、Matlab保存axes上的圖的問題(包括座標軸)... 88
4五、Matlab鼠標控制的兩個GUI例子(附代碼)... 91
4六、分享初學的一個GUI例子--新手好好看看(圖)... 97
4七、axes清除畫面... 113
4八、GUI中調用本身製做的幫助文件... 114
4九、關於從gui調用simulink. 114
50、如何將菜單中退出項和窗口關閉的回調函數合併?... 117
5一、matlab 日曆程序... 119
5二、如何在GUI裏得一個axes實現雙Y座標軸... 121
5三、如何實現動態的GUI界面... 121
5四、關於GUI和simulink參數傳遞和執行... 122
5五、代碼運行時間的計時方法... 134
5六、如何在GUI指定的axes中再畫一個axes. 135
5七、按下鼠標左鍵並拖動鼠標時的做圖方法... 136
5八、圖像處理相關資料... 137
5九、保存axes座標軸上畫的曲線或圖形... 140
60、在GUI中如何打開IE. 141
6一、gui輸入數據,經過rs232傳給芯片... 141
6二、Matlab關於gui和excel的問題... 142
6三、matlab 如何顯示數學公式... 145
6四、修改matlab自帶的tabdlg的字體和顏色... 148
6五、求助 Matlab的RGB彩色圖合成... 148
6六、如何刪除已繪製的曲線?... 149
6七、總結一下,MATLAB中隨機矩陣得到... 150
6八、【原創】GUI設計中背景音樂的定製與關閉... 153
6九、Matlab如何改變GRID 網格線的顏色?... 156
7一、把plot圖上的某些曲線排除在lengend以外,即不用legend標註出來... 157
7二、如何連續對矩陣追加數值... 158
7三、兩個等直徑圓管的交線... 160
7四、Matlab的csvread讀取數據的問題... 161
7五、在對數座標系插值的問題... 162
7六、實如今原有圖像上的部分圖像變爲白色... 162
7八、如何實現雙擊listbox中的條目才表示選中... 163
7九、如何刪除矩陣中的NaN. 164
80、用平行截面法討論由曲面z=x^2-y^2構成的馬鞍面形狀。... 164
8一、如何利用ode45解方程... 165
8二、Matlab圖片如何批處理?pic變量逐一讀取文件夾全部圖片名... 165
8三、方程爲:exp(-x)=cos(x),用迭代法求出最小的正根,當相對偏差<=10e-6時,求根結束。... 166
8四、經過鼠標點擊控制循環... 166
8五、圖像經連續小波分解後的顯示效果圖... 167
85-一、怎樣查看圖像的屬性... 169
8六、想產生以下的矩陣:6行10列,每行都是1 2 3 4 5 6 7 8 9 10。... 169
8七、textread讀取.txt中數據... 169
8八、數制之間的轉換怎麼實現... 170
8九、matlab讀取大數據文件的方法... 172
90、從狀態空間方程轉換爲傳遞函數... 174
9一、生成0 1 2 3 4 5 6 7 8 隨機出現大小爲20X20的矩陣!... 174
9二、存儲繪圖過程,並播放視頻... 175
9三、如何同時讀入多個文件,並做圖?... 175
9四、MATLAB GUI編程中幾個有用的程序段... 177
9五、Matlab如何在給定區域隨機取點?... 180
9六、數據如何導入到workspace中,並執行?在GUI裏面,怎麼傳遞處理。... 180
9七、matlab下畫‘心’的程序。... 181
9八、點到直線的距離怎麼求?... 181
9九、如何繪製正態分佈圖?... 185
100、matlab做圖時,如何只保存圖像而不顯示圖像... 185
10一、在三維圖中只顯示x,y軸,不顯示z軸... 186
10二、cell array和矩陣的顯示... 186
10三、矩陣形式的轉換... 188
10四、如何判斷鼠標是否在figure內的某一區域?... 189
10五、一個有用的程序... 189
10六、窗口的最大化、最小化、圖標、置頂... 191
10七、連續生成文件名的問題... 193
10八、編輯框edit中輸入公式後的繪圖問題... 194
10九、MATLAB中plot命令繪圖微調的幾個註記 (轉自職業倉庫)... 195
1十、MATlab 三維圖中顯示z座標軸的極大極小值... 203
1十一、如何一次性清空GUI程序的handles結構中的變量... 203
1十二、Matlab如何給元胞中的每一個一維向量前增長同一個數?... 204
11三、用guide生成的不一樣GUI之間控件的互相操做... 206
11四、自定義Matlab figure 工具欄按鈕... 208
11五、matlab 有沒有按某個小數位數作四捨五入的函數?... 209
11六、有關矩陣中小於某值的數取整的問題... 209
11七、Matlab表面被截後的部分... 210
11八、如何是imshow顯示的圖像充滿整個figure?... 211
11九、圖像顏色統計直方圖... 211
120、Matlab如何將大元胞數組寫入到txt文件... 212
12一、構造特殊矩陣(右螺線狀的)... 213
12二、figure中多座標軸中曲線的legend標註... 214
12三、GUI中鼠標選中並顯示曲線的類型及座標... 215
12四、Matlab中y=1\x圍繞y軸旋轉造成的旋轉曲面... 218
12五、GUI程序一開始以‘最大化’顯示的問題... 219
12六、如何實現文本自動轉換... 219
GUIDE生成的GUI的M文件控制了你編制的GUI界面的全部屬性和行爲,或者說外觀和對用戶操做的響應。好比說按下一個按鈕或者選擇了一個菜單項之類。M文件包括了運行你整個界面程序所須要的所有代碼,包括全部GUI組件的CALLBACKS函數。其實這些callbacks函數算是M文件裏的子程序,callback裏面就填寫你所指望程序作的動做,好比畫一個圖或者算一個算式。
插入,關於什麼是子程序 懂的人跳過^_^
function [avg, med] = newstats(u) % Primary function
% NEWSTATS Find mean and median with internal functions.
n = length(u);
avg = mean(u, n);
med = median(u, n);
function a = mean(v, n) % Subfunction
% Calculate average.
a = sum(v)/n;
function m = median(v, n) % Subfunction
% Calculate median.
w = sort(v);
if rem(n, 2) == 1
m = w((n+1) / 2);
else
m = (w(n/2) + w(n/2+1)) / 2;
end
以上就是一個大的程序function nestats,它下面另外包含了兩個小的function mean和median,這樣在大程序的裏面就能夠以如上的方式調用它們了。子程序的好處在於若是你老是要重複用到一組計算方式的時候,那你就把這組重複計算方式相似以上的方法編寫成一個子程序,避免大量重複代碼。在M文件裏面,會看到最外層,也就是最上面那一一行
function varargout = setfire(varargin)
(setfire是我m文件存的名字)就是那個大程序框,它下面有不少小function 好比什麼什麼creatFcn或者什麼callback之類。看上去那個複雜,其實就跟上面這個同樣的道理。只不過是M文件的相似avg = mean(u, n);med = median(u, n);這兩句話系統隱藏(就當它是隱藏好了)起來了,它會在你點擊鼠標(或者響應操做)時候自動去調用執行一次callback函數。因此你只用管把代碼寫入響應的函數名下就好了。至於系統爲何會自動調用,咱們不用管,咱們只用知道,我點擊鼠標,我拖動滑竿時,系統會執行哪裏的代碼。就夠了。
1、M文件的數據管理模式
Sharing Data with the Handles Structure :用handles這個東西共享數據
在你運行你的GUI的時候,M文件會自動生成一個叫作handles的東西(準確的說它屬於handles 類型的結構體,且取的名字也叫作handles),不用管那麼複雜,只用知道你能夠從它這裏找到GUI的全部數據,好比說控件的信息,菜單信息,axes信息。想象handles就是一個缸了,它裏面裝載了全部的信息,並且這個缸在各個控件的callback之間傳來傳去,理所固然那每一個控件的callback均可以放入一些想放入的數據,也能夠從裏面取出任何想要的數據包括別的控件的信息(好比滑竿的當前值,edit text的當前值)和別的控件放進去的數據。
因此,用handles能夠達到的目的有兩個:
a,各個控件的callback的信息交換
(current_data是隨便設置的變量名)
handles.current_data = X; 在某控件下的callback寫入這一句,就表示你把這個數據放缸裏了
guidata(hObject,handles);接着別忘了保存~!
而後在你須要的地方把它從缸裏撈出來
X1 = handles.current_data;
b,讀取GUI控件的信息,天然也能夠設置GUI控件的信息(好比說背景色隨着按鈕點擊而變換之類,或者你想讓按鈕A點一下,字符B跳一下,也行。)
all_choices是隨便取的變量名,my_menu是你那個菜單項的TAG名字
all_choices = get(handles.my_menu, 'String');
current_choice = all_choices{get(handles.my_menu, 'Value')};
這樣current_choice就獲得了用戶界面操做中,目錄或者菜單的選擇結果。
因此,要什麼信息,直接用handles.你的對象 就好了。
存什麼信息也直接handles.你的對象 就好了。
若是是本身的數據,就.變量名;若是是控件信息,就用get set
2、M-File裏的各個函數表明什麼意思
在設計面板設計排列好本身須要的各類按鈕或者編輯框以後,下一步任務即是添加本身的響應代碼。
Opening function 添加在它名下的代碼,在GUI開始運行可是還不可見的時候執行。這裏的代碼通常都是作一些初始化工做的。
Output function 若是有須要,能夠向命令行輸出數據。(這個函數我沒用過,很少說了^_^)
Callbacks 每一次點擊按鈕或者向輸入框輸入數據或者拖動滑竿,這些控件名下的callback就會執行一次。
函數的輸入參數
M-File名下的所有function都會有這兩個輸入參數
hObject 它表明的是當前的這個控件(也就是你點哪個按鈕或者拖的哪個滑竿)
handles 它表明的是如今這整一個GUI界面
對這兩個變量進行修改後
guidata(hObject, handles); 進行保存,不然修改無效;P
3、Opnning Function
這個函數名下的代碼 在界面可見以前執行。其實你也能夠在這個函數名下用handles.什麼tag 來得到組件的信息。由於在Opnning函數以前,全部的組件就已經生成了,只不過openning函數是把這些組件‘打開’,讓它們顯示出來。因此你能夠在這個函數下面,添加代碼,對界面作一些初始化工做。好比,計算一些數據,顯示一幅圖或者別的什麼工做。
function my_gui_OpeningFcn(hObject, eventdata, handles, varargin)
另外兩個輸入參數eventdata是matlab的保留參數,爲之後開發準備的,咱們不用管它。varargin 它裏面保存了,傳進來的命令行。
varargin怎麼理解呢?
-------------
my_gui('Position', [71.8 44.9 74.8 19.7])
%GUI也是函數,它只不過是有個界面的函數。它的調用,一樣是 函數名(輸入參數)。
這裏就表示GUI在打開時,位置這個屬性被設置成了右邊那個值。也就是在這個位置打開GUI。Position是你GUI界面的一個屬性。(要想知道各個控件有什麼屬性,在它上面雙擊就看到了。)因此一樣,也能夠用這種方式輸入其餘的初始化命令。
my_gui('路人甲','年十八')
但若是你輸入別的,左邊那個根本就不是界面的屬性名稱。這是輸入的參數就保存在varargin裏面。也就是 vararging{1}='路人甲' vararging{2}='年十八'。
這樣也能夠達到向調用的GUI傳入數據的目的。
4、Output Function
Output function 有輸入天然就有輸出,顧名思義,這個函數就是用來輸出的。
function varargout = my_gui_OutputFcn(hObject, eventdata, handles)
% Get default command line output from handles structure
varargout{1} = handles.output;
這個函數不是咱們本身編寫的,也不是咱們負責調用。咱們只用知道要傳出去的數據,實際上是放在vararout這個變量裏面的。可是咱們在別的控件的callback是叫不到vararout這個變量的,由於你去看這些callback的輸入參數裏並無vararout這個變量給它用。因此咱們只能間接修改handles.output這個變量。(固然在後面別忘了添加guidata(hObject, handles);保存修改)
由於默認的output函數裏面varargout{1}=handles.output,也就是修改了vararout。
(因此知道了原理,output只是一個名字而已,你也能夠用任意別的名字,或者添加更多的輸出變量,只要在outputFcn下面添加 varargout{2}=handles.第二個變量名 。。。。相似)
guidata(hObject, handles)以後不要當即delete窗口命令,由於這時候outputfcn沒有再執行一次,也就是你剛剛修改的output並無更新到varargin裏面去。 因此要麼單獨設計一個關閉按鈕;要麼跟uiwait(handles.figure1);uiresume合用。
5、Callbacks回調函數
當你對組件作點擊或者別的動做,則自動調用相應的callback。callback的名字取決於你的控件的tag和控件類型以及響應類型。
function print_button_Callback(hObject, eventdata, handles)
fig和m文件和見下,主要是用來導入數據(用於導入兩個文件夾中的txt文件,每一個txt有兩列,第一列時間,第二列電壓),運行後發現只能點擊一個pushbutton,當點擊第二個時會出現如下錯誤:
??? Undefined function or method 'fenbianlv1' for input arguments of type 'struct'. Error in ==> @(hObject,eventdata)fenbianlv1('pushbutton2_Callback',hObject,eventdata,guidata(hObject)) ??? Error while evaluating uicontrol Callback
應該是某個地方設置的問題。pushbutton裏面的函數體好像沒問題。就算在第二個函數體裏面只編寫一個很簡單的賦值語句也會出現一樣的錯誤,調試發現點擊第二個pushbutton時根本沒有進入到這個函數體內。好像是點擊了一個pushbutton後再點擊第二個pushbutton它就找不到這第二個pushbutton的callback函數了。但若是兩個pushbutton都編寫簡單的賦值語句發現沒有錯誤,說明第一個pushbutton的callback函數體代碼對第二個pushbutton的callback調用產生了影響,可是是什麼地方影響了一直髮現不了。
解決辦法:
是在pushbutton1和pushbutton2的回調函數裏用cd(dataRoute)把matlab的current directory的路徑給改了,數據讀取完成後,沒有恢復到原先的路徑,致使程序出錯。
讀取數據前先保存原先的路徑:
oldpath=cd;
數據讀完後再恢復原先的路徑:
cd(oldpath);
修改後的程序見實例程序:fenbianlv1.
剛學GUI,舉個例子,就是Pop_up Menus吧,他的回調函數是這樣的:
function=pushbutton1_Callback(hObject, eventdata, handles)
而後我想問的是:Val=get(h0bject,'Value')和Val=get(handles.pushbutton1,'Value');這兩個的值是同樣的嗎,若是是同樣的,那h0bject和handles在使用時有什麼區別?
答:
在MATLAB GUI中,數據分兩種:GUI data和application data。 兩種數據的存取機制是相同的,可是GUI data使用起來比較方便。
每個GUI 圖形界面都維持一個和本身的界面的圖形(figure)相聯繫的一個handles數據結構,這個數據結構中容納圖形界面內全部控件(按鈕、列表框、編輯框等)的句柄,至關於一個大的「容器」,裏面存放了figure內全部控件的句柄。同時,handles結構也能夠被figure內全部控件的回調函數訪問,由於回調函數的輸入參數中都有handles結構。此外,在控件的回調函數內能夠把數據存儲到handles結構中。
handles結構數據的取得和存儲是經過guidata函數來實現的。
例如:在編輯框edi的回調函數內想得到t編輯框的句柄,hObject能夠,也能夠用handles.edit,這兩個值是同樣的,沒有區別,只不過得到控件句柄的方式不一樣而已:hObject是調用回調函數時直接傳過來的,handles.edit是從handles結構中取得的。可是,在控件的CreateFcn函數中若是想訪問控件,必須用hObject,而不能用handles.edit,由於這時控件還沒被建立,其句柄尚未加入到handles結構中。
各控件的回調函數中,hObject的值是不同的,分別表明調用回調函數的控件的句柄,而handles結構倒是同樣的。這種機制便於figure內的不一樣控件的回調函數內傳遞數據。
1、問題1:
>> handles.axes1=axes('tag','tag1');
delete(handles.axes1);handles
handles =
axes1: 0.027
figure中的座標軸已經被刪除了,
可是爲何handles.axes還存在?
還有運行下面出錯:
>> get(handles.axes,'tag')
??? Reference to non-existent field 'axes'.
問題癥結:
delete(handles.axes1)是刪除了和handles.axes1句柄相關聯的對象,可是handles結構沒有清空,其中仍然有axes1句柄的數值。只是這個句柄已經失效了,由於沒有對象和它關聯了。因此,你再用get或set想得到或設置對象的屬性時就會出錯。
另,設定的是handles.axes1,不是handles.axes,因此提示在handles結構中不存在axes這個句柄,而不是無效的句柄(invalid handle object)。
get(handles.axes,'tag') ??? Reference to non-existent field 'axes'.
2、問題2:
matlab help的一個例子:
% Create figure to use as GUI in your main function or a subfunction
figure_handle = figure();
% create structure of handles
myhandles = guihandles(figure_handle);
% Add some additional data as a new field called numberOfErrors
myhandles.numberOfErrors = 0;
% Save the structure
guidata(figure_handle,myhandles)
不是很明白guidata的用法,figure_handle和myhandles之間是什麼關係?是如何進行保存的。
答:
這就是GUI裏面的句柄和包含句柄的結構之間的區別。
figure_handle是和所建立的figure相關聯的句柄,經過語句
myhandles = guihandles(figure_handle);
所得到的是和figure_handle句柄相關聯的一個結構,此結構包含了該figure內全部控件的句柄,
好比:菜單、工具條等等控件的句柄,其中也包含figure_handle這個句柄。myhandles結構能夠
儲存與GUI有關的一切數據。
guidata(figure_handle,myhandles) 是保存與figure的句柄figure_handle相關聯的myhandles結構。
利用定時器連續顯示圖片,裏面用的是image函數,但image函數顯示圖片大小會失真。因而改用imshow函數,能解決大小失真的問題。但每次點擊播放,都會彈出可惡的窗口。調試發現,發現每次調用imshow時都彈出來。搞不清問題出在哪裏。如下是圖像播放的代碼:
function picture_play(hobj,event,handles)
global filename1;
global pathname1;
global number_of_file1;
global index1;
global A;
index1=index1+1;
if index1==number_of_file1+1
index1=1;
end
A=imread([pathname1,filename1{index1}]);
cla;
imshow(A,'parent',handles.axes4);
strFileName=fullfile(pathname1,filename1{index1});
set(handles.filename_edit,'string',strFileName);
解決辦法:
通過調試,追蹤imshow函數的內部,終於找出了問題:
打開figure的屬性編輯器,可見fugure的‘HandleVisibily’屬性值默認爲‘callback’,把它改成‘on’;同時確保‘NextPlot’的屬性值爲‘add’,問題解決。
另,新建的figure對象的HandleVisibily’屬性,默認值都爲callback。
幫助文件說,這是matlab採起的一種保護措施,HandleVisibily’屬性值默認爲‘callback’,figure的句柄只對其所包含控件的回調函數來講是可見的。這也多是imshow和image函數在處理這一問題上的不一樣吧。
注意:相似的問題之前在論壇中也有會員提出過:
如何把波形繪製到指定的座標軸上?發表於 2007-11-21 11:27 AM
在GUI作了一個有三個座標軸的界面,用於顯示從串口接收到的數據。
串口設置以下:
g = serial('COM1') ;
g.InputBufferSize= 4096;
g.OutputBufferSize= 4000;
g.BaudRate= 9600;
g.BytesAvailableFcnMode = 'byte'; %中斷觸發事件爲’bytes-available Event’?
g.BytesAvailableFcnCount = 45; %接收緩衝區每收到45 個字節時, 觸發回調函數
g.BytesAvailableFcn = @instrcallback; %獲得回調函數句柄
回調函數instrcallback的繪製波形部分程序以下:
t =1:1:4;
axes(Ch1_Dis); %Ch1_Dis爲座標軸1句柄
hold on
plot(t,ch1);
axes(Ch2_Dis); %Ch2_Dis爲座標軸2句柄
hold on
plot(t,ch2);
axes(Ch3_Dis); %Ch3_Dis爲座標軸3句柄
hold on
plot(t,ch3);
可是每次經過串口觸發回調函數instrcallback時,執行到plot指令都會另建一窗口figure1,將波形繪製到另建的窗口中。
當不經過串口觸發回調函數,而是在一按鈕的回調函數中調用instrcallback時,就會把波形繪製到指定座標軸中。
利用gtext函數。
gtext displays a text string in the current figure window after you select a location with the mouse.
gtext('string') waits for you to press a mouse button or keyboard key while the pointer is within a figure window. Pressing a mouse button or any key places 'string' on the plot at the selected location.
若是edit是多行的。想點擊每一行的時候,能執行不一樣的事件,那麼能夠使用:
contents=get(hObject,'String');
a=contents(get(hObject,'Value'))
那麼a就是你選擇的對應的那一行。
(1)使用imrect和imcrop函數相結合,就能夠實現截圖功能。
用imcrop函數,例如:
I = imread('circuit.tif');
I2 = imcrop(I,[60 40 100 90]);
figure, imshow(I)
figure, imshow(I2)
見本身編寫的程序:picturecrop。
(2)剪取圖像的中間區域:我想裁剪圖像中間的部分,就是去掉圖像周圍部分!
一、首先取得圖像的顯示範圍:
x1=get(gca,'xlim');
y1=get(gca,'ylim');
width=x1(1,2)-x1(1,1);
height=y1(1,2)-y1(1,1);
二、求的圖像中心的座標:
x0=x1(1,1)+width/2;
y0=y1(1,1)+height/2;
三、若是想剪切圖像顯示區域的1/4(以圖像中心向四周剪切),則:
a=width/4;
b=height/4;
四、計算裁剪區域:(以圖像中心點爲裁剪中心)
rect=[x0-a/2 y0-b/2 a b]
五、用imcrop裁剪:
a=imcrop(A,rect);
用兩個矩陣畫了一個圖像,用grid on添加了網格,可是默認的網格太稀了,想要密一點的,該怎麼解決?
1、用 set(AX,'XMinorGrid','on');set(AX,'XMinorGrid','on');
二、(1)控制座標軸尺度長度:set(gca,'XLim',[-pi/2 pi])
(2)定製本身想標註的刻度:
set(gca,'XTick',[-pi/2:pi/4:pi]) %%%座標軸最小值,步長,最大值
3、xlabel(‘x軸’,’rotation’,45);%x軸文字的方向,0爲水平方向,90爲垂直方向
4、將座標的x軸作成10 的4次方,而不是10000這種形式。
set(gca,'xlim',[0 10e4]);
解決辦法:
例子:例如想創建三行三列的table,而且要求第三列是可編輯的,其它兩列是不可編輯的,
代碼以下:
f = figure('Position',[100 100 400 150]);
dat = {6.125, 456.3457, 2.30;... %初始化各列的數值
6.75, 510.2342, 1.31;...
7, 658.2, 3.52};
columnname = {'Rate', 'Amount','Value'}; %各列的名稱
columnformat = {'numeric', 'bank', 'numeric'}; %各列的數據類型
columneditable = [false false true ]; %各列是不是可編輯的,true是能夠編輯,false是不可編輯
t = uitable('Units','normalized','Position',...
[0.1 0.1 0.9 0.9], 'Data', dat,...
'ColumnName', columnname,...
'ColumnFormat', columnformat,...
'ColumnEditable', columneditable);
顯示結果以下:
其中,第三列的數值是能夠編輯的。
將在Matlab下編寫的GUI轉成獨立於Matlab平臺的應用程序Standalone Application。
具體過程:
目的是把一個Matlab GUI轉成Standalone Application即不在Matlab平臺下也可打開。
用的GUI文件見:單純形法實現(GUI based on Matlab)http://www.ilovematlab.cn/viewthread.php?tid=7634&highlight=%2Bfaruto
首先新建:File——》New——》Deployment Projiect,出現以下界面:
選擇Standalone Application
在main function 中添加要轉化的M文件:
單擊Build project
等待編譯完成:
編譯完成後,在工做目錄下會生成相關項目的文件夾:
其中distrib中有生成的.exe文件:
運行該.exe文件便可(這個.exe文件就是一個Standalone Application)。
最後生成的Standalone Application:[attach]8930[/attach
要將用Matlab語言編寫的函數文件編譯成可獨立執行的*.exe文件(便可脫離Matalab環境的執行程序),首先要安裝和配置好Matlab Compiler,通常來講,在安裝Matlab時就已經安裝了相應版本的Matlab Compiler。只是不一樣版本的Matlab,其編譯器的使用方法有必定的差別,這一點要引發必定的注意。
在肯定安裝好Matlab Compiler後,還須要對Compiler進行適當的配置,方法是在Matlab命令窗口輸入:
Mbuild –setup
而後根據提示執行相應的操做,使用者可根據本身計算機中現有編譯器的狀況選擇合適的編譯器,如VC++ 6.0、VC++7.0、Bland C的編譯器等,目前Matlab好象還不支持VC++8.0(我計算機安裝的就是VC++2005,Matlab就沒法識別)。固然,若是你的計算機里根本就沒有安裝其餘任何語言的編譯器,也可選擇Matlab自帶的Lcc編譯器,其實這個編譯器對大多數用戶已經夠用了(我就是選擇的Matlab自帶的Lcc編譯器)。
配置好編譯器後,天然就是對本身編寫的M文件進行編譯了。
將M文件編譯爲獨立可執行文件的語法是:
>>mcc –m fun1.m fun2.m…..
其中fun1就是最後的可執行文件的名稱。
另外,也可經過採用命令開關-o指定編譯最終目標文件的名稱,如 mcc –m main.m –o mrank_main,就是將編譯後的文件指定爲mrank_main.exe。
編譯後的生成文件根據編譯器的版本不一樣而不一樣。具體的可參閱相關資料。
若是要在沒有安裝matlab的計算機上執行編譯後的程序,首先要將\MATLAB701\toolbox\compiler\deploy\win32中的MCRinstaller.exe安裝到該計算機上(7.0之前的版本是mglinstaller.exe)。
其次是要將「MCRinstaller.exe安裝目錄\runtime\win32」這個路徑添加到該計算機的環境變量中,添加的方法是:
右擊「個人電腦」「屬性」「高級」「環境變量」「添加」指定一個變量名,而後將上述路徑複製到裏面就能夠了。
第三步是將編譯生成的相相關文件拷貝到同一目錄下(固然其餘目錄亦可)。
第四步是打開MS-dos操做窗口,進入到編譯後的*.exe程序所在的目錄,執行編譯生成的*.exe文件便可。
須要說明的一個問題:
若是你的程序還附帶有圖片(如Version上的圖標)、Web頁面(如help文檔),在編譯的時候可能沒法與M文件一塊兒編譯(由於我沒有試過,也沒有看到有關這方面的介紹),這沒有關係,先在計算機上執行一次你編譯後生成的獨立可執行文件,這時在同一目錄下會生成一個以你編譯後的程序名+_mcr結尾的文件夾,這時,你只須要把與程序相關的圖標和Web頁面拷貝到該文件夾中的Matlabprogram下面的一個子目錄(通常與用於編譯的文件夾名相同)中便可。
其餘的方法還有:(如下是網上搜索到的方法,沒有試驗過,有興趣的朋友能夠試一試)
方法一:在matlab下的workspace裏打comtool,點file-open project將咱們先前建好的comtest.cbl工程文件打開,再點component--package component就實現了打包,此時到comtest\distrib文件夾裏看,生成的comtest.exe就是打包後的解壓程序,雙擊它會解壓出一些文件,再點擊解壓出來的_install.bat就能夠實現安裝
方法二:如何將gui生成exe ?
已有gui.m文件和gui.fig文件
1 在matlab的command窗口中輸入
mcc -B sgl GUI.m
2.將上步生成的文件包括*.m 文件和*.fig文件一塊兒考到待運行的機器
此時仍需matlab所必需的動態鏈接庫。
3. 將 <matlab path >/extern/lib/win32/mglinstallar.exel拷貝到到待運行機器上
4.在機器上先運行mglinstallar.exe, 而後選擇解壓目錄,將在指定目錄下解壓縮出bin和toolbox兩子目錄,其中在bin\win32目錄下就是數學庫和圖形庫脫離MATLAB運行所需的全部動態鏈接庫,共有37個。能夠將這些.dll考入system32, 也能夠直接放在應用程序目錄下。而toolbox目錄則必須與應用程序同一目錄。
5.大功告成。
matlab生成獨立可執行的程序
引用
靈夢捕手 的 matlab生成獨立可執行的程序
1、生成獨立可執行的程序(exe文件)步驟
一、安裝編譯器。可有多種選擇,本機安裝的是microsoft visual c++ 6.0;
二、設置編譯器。在matlab命令行輸入mbuild -setup,選擇安裝的c編譯器;
三、調用編譯器。輸入mcc -m filaname,filaname爲要轉成exe的m文件;
在之前的版本中,用編譯命令mcc -B sglcpp filaname;自2006的版本後,替換爲mcc -m filaname;
四、安裝MATLAB7\toolbox\compiler\deploy\win32目錄下的MCRInstaller。
2、脫離matlab運行可執行程序
MCR是由matlab的運行環境,佔用不到400M的對於用不一樣matlab版本生成的exe文件,MCR版本也會有不一樣,所以,在程序打包時,最好將相應版本的MCR一塊兒打包。MCR環境的設置文件存放目錄以下:
\MATLAB\R2007a\toolbox\compiler\deploy\win32
文件名爲MCRInstaller.exe。可將其拷貝到本身的文件夾中。
在其它機器上運行exe文件前,首先安裝matlab的運行環境。在同一機器上能夠並存不一樣版本的matlab環境。
Note: 將MCRInstaller.exe拷貝到你文件所在文件夾裏,用打包程序來打包,生成安裝文件,設定在解包過程當中自動執行MCRInstaller.exe,同時將可執行文件的圖標放在桌面。
1.設置編譯器:
在肯定安裝好Matlab Compiler後,還須要對Compiler進行適當的配置,方法是在Matlab命令窗口輸入:
Mbuild –setup, 按提示選擇matlab自帶編譯器LCC。
2.將腳本編譯爲可執行文件:
如項目文件包含:gui.m, gui.gif, fun1.m。
在此路徑下命令行輸入:mcc –m gui.m,生 成:mccExcludedFiles.log,ReadMe.txt,gui.ctf,gui.prj,gui_main.c,gui_mcc_component_data.c,gui.exe。其中:gui.ctf,gui.exe爲脫離matlab環境運行必需的文件。
3.在未安裝matlab的機器上運行可執行程序。
將R2 2007b\toolbox\compiler\deploy\win32中的MCRinstaller安裝到該計算機上,將生成可執行程序脫離matlab運行所需的函數庫。
將2中生成的gui.ctf,gui.exe拷貝到該計算機同一路徑。運行gui.exe將生成gui_mcr文件夾,包含程序運行所需的庫。至此完成。
4.去除獨立可執行程序運行時的「DOS黑窗口」。
以上生成的exe程序運行時首先彈出一個DOS界面窗口,若是不須要其輸出數據和錯誤信息,可將其去除。
matlba命令行輸入:
cd(prefdir) edit compopts.bat
此時compopts.bat打開,在文件最後添加:
set LINKFLAGS=%LINKFLAGS% -subsystem windows
若是程序比較複雜,易出現異常,則不建議去除這個dos窗口以便調試。
另外,這個辦法是適用於你用的編譯器爲LCC,若是是其餘的,那麼所加語句有所不一樣
Microsoft Visual C/C++:
set LINKFLAGS=%LINKFLAGS% /SUBSYSTEM:WINDOWS
/ENTRY:mainCRTStartup
Borland:
set LINKFLAGS=%LINKFLAGS% -aa
5.遇到某些函數不能使用的問題。
個人程序中用到vpa函數,運行gui.exe出現:undefined method or function 'vpa' for input argument type of 'double'錯誤提示。而gui.m腳本在matlab環境能夠運行。
緣由:百度搜到的信息爲:matlab不支持符號工具箱的編譯。只好避開使用此函數。
「將MCRInstaller.exe文件、file.ctf文件和file.exe文件打包,粘貼至目標機器上後,解壓,運行MCRInstaller.exe,將file.exe和file.ctf複製到應用目錄下,添加目錄<mcr_root>\runtime\win32到用戶系統路徑(<mcr_root>爲MCR安裝路徑。」)
1)這就話中「將file.exe和file.ctf複製到應用目錄下」是隻哪一個應用目錄;
2)「添加目錄<mcr_root>\runtime\win32到用戶系統路徑(<mcr_root>爲MCR安裝路徑。)」怎樣添加目標到用戶系統路徑。
問題1:.exe和ctf在同一個目錄就能夠,就是隻要在同一個文件夾就行的。
問題2:用戶系統路徑的添加是在環境變量裏,個人電腦——>屬性——>高級——>環境變量,添加便可。
最近在論壇上學習,雖然進度很慢,但收穫很多!
如今將我在學習過程當中對於GUI控制simulink時遇到過困難的一些功能作成一個綜合實例放在這裏,打個包但願給你們省點錢,也但願可以幫助到論壇裏須要的朋友!同時以此感謝在我學習的過程當中熱心幫助過個人朋友們,感謝論壇! GUI and Simulink.rar (14.88 KB)
該實例主要功能:
一、演示了GUI界面的佈局和效果;
二、演示了togglebutton、pushbutton對simulink模塊參數的設置方法;
三、演示了Edit text 和slider的聯合使用,及利用edit text 和slider 對simulink 參數的動態修改;
四、演示了simulink參數在GUI上的顯示和更顯;
五、語句進行了註釋,爲便於編譯沒用中文,你們湊或者看吧!
管理員:「會員RayneZ提醒:該帖子的樓主貼了一個GUI+Simulink的示例文件,可是有些小錯誤,matlab在運行的時候提示出錯。
檢查了一下,錯誤緣由在GUI_ex11.mdl這個文件中的fcn2模塊中的函數編寫有些問題
第四行和第六行的邏輯判斷語句中的&應該改成&&
更改後程序能夠正常運行。
想在一個axe上顯示一張圖,在點擊的時候放大圖片我使用的是imshow函數。當沒有顯示圖像的時候,單擊axe有反應,可是一旦imshow以後單擊就沒有任何反應了請問怎麼解決呢?
解決辦法:
調試了一下,能夠解決的。方法以下:
(1)在你的GUI的OpeningFcn函數中加入以下代碼:
axes(handles.axes1);
Image=imread('C:\Users\liuhuanjin\Pictures\5HPQ1IFA00AN0001.jpg'); %讀取圖像
hImage=image(Image); %顯示圖像,同時取得圖像的句柄(handle)
handles.hImage=hImage;%保存圖像的句柄到handles結構,以備後用
guidata(hObject,handles);
set(hImage,'ButtonDownFcn',{@myCallback,5}); % 設置圖像對象的
ButtonDown回調函數爲本身定義的myCallback,並將5做爲參數傳遞給它。
(2)在本身定義的myCallback函數中加入代碼:
function myCallback(hObject,eventdata,arg1)
........%在此加入你的代碼
由於圖像顯示後你點擊的是圖像,因此axes的那個ButtonDownFcn回調函數並無調用。
關於自定義的callback的參數傳遞方法有:
Callback Function Syntax |
How to Specify as a Property Value |
function myfile |
set(h, 'StartFcn', 'myfile') |
function myfile(obj, event) |
set(h, 'StartFcn', @myfile) |
function myfile(obj, event, arg1, arg2) |
set(h, 'StartFcn', {'myfile', 5, 6}) |
function myfile(obj, event, arg1, arg2) |
set(h, 'StartFcn', {@myfile, 5, 6}) |
(另外有用的代碼)
axes(handles.axes2);
iptsetpref( 'ImshowAxesVisible' , 'on' ); %顯示座標軸set(zoom,'Direction','In','Enable','on'); %顯示放大圖標
Image=imread('C:\Users\liuhuanjin\Pictures\5HPQ1IFA00AN0001.jpg');
hImage=image(Image);
set(hImage,'ButtonDownFcn',@myCallback);
handles.hImage=hImage;
有一個循環用來採集數據的,想加入一個waitbar而且在waitbar上加入按鈕,在取消的同時停止循環不知怎麼能實現。
stop=false;
h = waitbar(0.0,'Please wait...','CreateCancelBtn','stop=true; delete(h); clear h');
set(h,'Name','optional window name');
for i=1:1000
waitbar(i/1000,h,['Update ' num2str(i)]);
if stop
break;
end
% do stuff
end
效果以下:
另:waitbar的closeFcn如何設置
對循環過程加了一個waitbar同時加了一個Cancel按鈕這個按鈕能夠停止循環可是要是在waitbar上點擊關閉按鈕,卻會出現沒有找到closeFcn的錯誤。想加closeFcn而且讓他和cancel按鈕起同樣的做用這個怎麼實現?
解決方法:
須要的功能是經過CloseRequestFcn 實現的,由於每次執行(點X)這個動做,系統是執行了CloseRequestFcn 。在你的m文件裏,覆蓋(override)這個函數就能夠。
Help文檔裏,有這方面的例子。
好比說,當用戶 點 X, 你能夠彈出一個對話框,確認是否是要關閉,你能夠定義一個函數,my_closereq:
% my_closereq
% User-defined close request function
% to display a question dialog box
selection = questdlg('Close Specified Figure?',...
'Close Request Function',...
'Yes','No','Yes');
switch selection,
case 'Yes',
delete(gcf)
case 'No'
return
end
而後,在系統初始階段,加上:
set(figure_handle,'CloseRequestFcn','my_closereq')
因此,只要修改my_closereq,符合本身的要求就能夠了。
1. % --- Executes on button press in fft.
2. function fft_Callback(hObject, eventdata, handles)
3. global pathname filename sf nfft outfile H1 H2;
4. fid=fopen([pathname filename],'r');
5. x=fscanf(fid,'%f',[1,inf]); %按行讀入原始信號數據
6. %FFT變換
7. nt=length(x);
8. h=findobj('Tag','cypl');
9. sf=str2double(get(h,'string'));
10. h=findobj('Tag','nfftcd');
11. nfft=str2double(get(h,'string'));
12. y=fft(x);%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
13. %繪製輸入曲線圖形
14. t=0:1/sf:100/sf;
15. plot(H1,t,x(1:101));
16. xlabel('時間(s)');
17. ylabel('幅值');
18. title('輸入數據的時程曲線圖')
19. grid on;
20. %繪製幅頻曲線圖
21. f=0:sf/nfft:(nt-1)*sf/nfft;
22. plot(H2,f,abs(y));
23. axis([0,(nt-1)*sf/(nfft*2),3*min(y)/2,3*max(y)/2])
24. xlabel('頻率(Hz)');
25. ylabel('幅值');
26. title('信號頻譜圖');
27. outfile=y;
28. grid on
29. %grid on;
30. %h = findobj('tag',axes1)
31. % hObject handle to fft (see GCBO)
32. % eventdata reserved - to be defined in a future version of MATLAB
33. % handles structure with handles and user data (see GUIDATA)
函數定義以下所示。
使用方法爲:
figure(1);
subplot(211), hline = plot(sin(1:10));
subplot(212), plot(sin(1:100));
dynpoint(hline);%調用函數時把hline句柄值傳給函數
界面:
==========================================================
function dynpoint(arg,h)
% Show the coordinates of a plot dynamically
%
% To start use:
% dynpoint(h)
% where h is a handle to a figure, axes or e.g. line.
%
% To delete use:
% dynpoint('delete',h)
% where h is a handle to a figure, axes or e.g. line.
% (you may also use: dynpoint delete)
%
% There can only be one dynamic plotter in a figure at a time.
%
% Example:
% subplot(211), hline = plot(sin(1:10))
% subplot(212), plot(sin(1:100))
% dynpoint(hline)
% 2002,6.29
if ~exist('arg','var')
arg = gcf;
end
if ~isstr(arg)
handle = arg;
arg = 'init';
end
switch arg
case 'init'
if ~ishandle(handle)
error('h is not a handle')
end
[h,ax] = h2hax(handle);
% delete old dynamic text object
ht = findobj(h,'tag',[mfilename '_text']);
if any(ht)
delete(ht)
end
% text window at the bottom left corner
% text in centred
uicontrol(h,...
'style','text',...
'pos',[10 10 100 40],...
'tag',[mfilename '_text'],...
'userdata',ax(1))
% do the dynamic thing...
set(h,'windowbuttonmotionfcn',[mfilename ' move'])
case 'move'
ht = findobj(gcbf,'tag',[mfilename '_text']);
ax = overobj('axes');
if ~any(ax)
ax = get(ht,'userdata');
end
p = get(ax,'currentpoint');
set(ht,'string',sprintf('%g %g', p(1),p(3)));
case 'delete'
if ~exist('h','var')
h = gcf;
end
[h,ax] = h2hax(h);
set(h,'windowbuttonmotionfcn','')
ht = findobj(h,'tag',[mfilename '_text']);
delete(ht)
end
% ----------
function [h,ax]=h2hax(handle)
typ = get(handle,'type');
if strcmp(typ,'figure')
h = handle;
ax = findobj(h,'type','axes');
elseif strcmp(typ, 'axes')
h = get(handle,'parent');
ax = handle;
elseif strcmp( get(get(handle,'parent'), 'type'), 'axes' )
ax = get(handle,'parent');
h = get(ax,'parent');
end
=========================================================
我要的數據是保存在一組具備相同前綴名*.dat,*.atr,*.hea中的。只有3個同時被使用,數據才能起做用。
我想作一個的界面,一個最基本的功能就是「打開」按鈕,它的做用是打開*.dat文件,並匹配和*.dat具備相同文件名的另外兩個文件:*.atr,*.hea。實際上就是我表面上只是打開了那個*.dat文件,但程序會搜索和*.dat具備相同文件名的另外兩個文件:*.atr,*.hea,一塊兒打開,並把它們保存在3個變量裏。
如今的困難是如何在同一個文件夾裏搜索到另外兩個文件?
解決方法:
一、給你個例子:
fileDir='C:\Users\liuhuanjin\Documents\MATLAB';
fileName='mydata.dat';
files = dir(fileDir); %列出文件夾中的全部文件,保存到files結構中
for i=1:length(files)
if (strcmp(files(i).name,fileName)==1) % 查找想要的文件
fullFileName=[fileDir '\' fileName];
disp('Find the file!');
return
end;
end;
disp('Can not find such file');
二、%2.
打開圖片
[filename,pathname]=uigetfile(...
{'*.bmp;*.jpg;*.png;*.jpeg;*.tif','文件類型(*.bmp,*.jpg,*.png,*.jpeg,*.tif)';...
'*.*', '全部文件(*.*)'},...
'Pick an image');
axes(handles.axes1);%用axes命令設定當前操做的座標軸爲axes1;
fpath=[pathname filename];%將文件名和目錄名組成一個完整的路徑;
I=imread(fpath);imshow(I);%用imread讀入圖片保存變量爲I,而且imshow在axes1軸上顯示
set(handles.getcurrentpoint_pushbutton,'Enable','on');%使其在打開命令使用後可以使用,放在打開函數最後。%3.
讀取在上面打開圖片目錄下的
txt
文件內容。
file=ls([pathname, '\*.txt']);%文件名
for i = 1 : size(file, 1)
filepath{i} = strcat(pathname, '\', file(i, :));
%合併路徑及文件名
end
for m = 1 : length(filepath)
a=importdata(filepath{i},'\t');
for i=1:(size(a,1)-2)
a{i}(~((a{i}>='0' & a{i}<='9') | a{i}=='.'|a{i}=='-'|a{i}==':'))=' ';
end
三、
[filename1,pathname]=uigetfile(...
{'*.dat','Data Files(*.dat)';...
'*.*','All Files(*.*)'},...
'Pick an dat');
name=filename1(1:end-4);
filename2=[name,'*.atr'];
filename2=[name,'*.hea'];
data1=load([pathname,filename1]);
data2=load([pathname,filename2]);
data3=load([pathname,filename3]);
這樣就能夠了,剩下的你本身寫
本人作了一4個button用於打開4個矩陣文件,第五個button用於把前四個button的數據寫到一個矩陣中去。本人想實現若只輸入前3個button的數據,第4個button不導入任何數據,如何實現第5個button能把前3個button的數據也寫到一個矩陣中去。如下是本人編的的條件語句,很差使啊!說明一下數據傳遞用的guidata型。
a=handles.a;
b=handles.b;
c=handles.c;
d=handles.d;
if isempty(d)
A=[a b c];
else
A=[a b c d];
解決方法:
按照你的描述,我編了個程序,能夠實現你所說的功能。
首先在Openingfcn中初始化矩陣d爲空矩陣;
而後在各按鈕的回調函數中加入形如以下格式的語句:
handles.a=rand(3,3); % 隨機生成3*3矩陣作測試
guidata(hObject,handles);
最後在第5個按鈕的回調函數內加入以下代碼:
a=handles.a;
b=handles.b;
c=handles.c;
d=handles.d;
if isempty(d)
A=[a b c];
else
A=[a b c d];
end
當不按按鈕5時,d爲空矩陣,則輸出前三個矩陣;當按了按鈕5時,d被賦值,不爲空,則輸出a,b,c,d四個矩陣。
請教:讓push button執行一個程序的simulation, 在界面得全部edit box裏輸入相關數據後,想要直接按回車鍵 不用鼠標點擊pushbutton 就能夠直接執行, 該怎麼編輯push button的callback呀
解決方法:
(1)設置控件的tab order。程序運行後,用tab鍵選定pushbutton,直接按"空格鍵",不用點擊pushbutton就能夠;
(2)在最後的edit控件的callback函數內加入執行simulation的命令,最後的edit控件輸入完成後直接按'回車鍵'就能夠運行simulation;或者調用button按鈕的callback也行。
(3)在KeypressFcn函數內加入相應的命令。這個方法仍是須要在edit內輸入完數據後,在figure的空白處點一下鼠標,而後按鍵盤的任意鍵才行。
根據你的意思,你是不想用鼠標點button按鈕,按enter就執行button內的代碼,那第(2)種方法是可行的。以上方法經實際測試,均是可行的!
我編了一個GUI, 使用的時候會須要輸入一些數據, 我放了一個editbox和一個按鈕"Enter", 用的時候就是在editbox裏面輸入數據, 而後按"Enter"確認. 如今問題就是輸入好數據,按了Enter以後, editbox裏面的數據還在, 下次再輸入的時候就要先刪除後再輸入, 我想問一下有沒有什麼辦法可以讓按了Enter鍵以後, editbox裏面的數據就會清除掉, 這樣下次再輸入的時候就不用先刪除了。
在enter按鈕的回調函數里加入以下代碼處理便可:
value1=get(handles.edit1,'string');%先取得編輯框的數據
set(handles.edit1,'string','');%再把編輯框清空
問題:GUI設計的結果怎麼用EXCEL來保存到指定的文件夾。
說明:根據論壇上的例子作了個GUI界面,結果能夠保存到EXCEL裏面,但保存的路徑只能是在當前文件夾,我但願保存到指定的文件夾,怎樣才能把數據結果以EXCEL表格的形式保存到指定的文件夾?高手指點一下,不勝感激。。。
解決方法:
例如:要把‘第一行’、‘第二行’、‘第三行’分別添加到excel表格的三列可開頭,用如下命令:
M={‘第一行’,’ 第二行’,’ 第三行’};%定義爲cell類型
xlswrite(‘myexcel.xls’,M);
結果:
1
、
a=get(handles.edit1,'string');
b=get(handles.edit2,'string');
m={a;b};
[filename, pathname] = uiputfile('*.xls', '保存計算結果');
if filename==0 % 取消
return;
end
oldpath=cd;
cd(pathname);
[pathstr,filename]=fileparts(filename);
xlswrite(filename,{'X取值:'},'sheet1','A1');
xlswrite(filename,{'y=x^3+x^2+x的結果:'},'sheet1','A2');
xlswrite(filename,m,'sheet1','B1:B2');
cd(oldpath);
二、
a=get(handles.edit1,'string');
b=get(handles.edit2,'string');
m={a;b};
[filename, pathname] = uiputfile('*.xls', '保存計算結果');
if filename==0 % 取消
return;
end
[pathstr,filename]=fileparts(filename);
xlswrite(filename,{'X取值:'},'sheet1','A1');
xlswrite(filename,{'y=x^3+x^2+x的結果:'},'sheet1','A2');
xlswrite(filename,m,'sheet1','B1:B2');
在popupmenu下拉菜單中有許多行內容,如何獲得最後一行的value值?
解決方法:
在popupmenu的回調函數中加入代碼以下:
function popupmenu1_Callback(hObject, eventdata, handles)
list_menu=get(handles.popupmenu1,'String'); %先獲得存放菜單項的cell列表
string=list_menu{end}; %獲得最後菜單項的字符串
value=length(list_menu);%獲得最後菜單項的Value值
disp(value);
或者用如下代碼:
str=get(handles.popupmenu1,'string');
s=str(end) %最後一行內容
val=size(str,1) %最後一行所處行數
想在一個按鈕的回調函數下運行另外一個回調函數,句子該如何寫?
就像以下調用就能夠。回調函數沒有什麼特別的,也是普通的函數,只不過它是響應控件的操做的。
解決方法:
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to mybutton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
pushbutton2_Callback(hObject, eventdata, handles);
% --- Executes during object creation, after setting all properties.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to mybutton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
t2_1=get(handles.edit_t21,'String')
t2_2=get(handles.edit_t22,'String')
ua=get(handles.edit_ua,'String')
phi=get(handles.edit_phi,'String')
a_bmax=phi*9.8
s_zhidong=(t2_1+t2_2/2)*ua/3.6+ua^2/25.92/a_bmax
set(handles.text_zhidongjuli,'String',num2str(s_zhidong));
問題出如今:
a_bmax=phi*9.8這句不對,由於phi=get(handles.edit_phi,'String')是從edit控件中返回字符串,必須用str2double或str2num轉換爲數字類型後才能使用。
pushbutton實現下面的功能:
先判斷edit(3個)是否是爲空,接着讀取popupmenu中的信息(2個選項),當二者都符合要求的時候執行相關的命令這樣的pushbutton的callback怎麼寫呀,我寫的
a=get(handles.edit1,'string');
b=get(handles.edit2,'string');
c=get(handles.edit3,'string');
if isempty(a) || isempty(b) || isempty(c)
warndlg('編輯框爲空!')
else
% 運行下面的代碼
end
解決方法:
a=get(handles.edit1,'string');
b=get(handles.edit2,'string');
c=get(handles.edit3,'string');
val1=get(handles.popupmenu1,'Value');
str1=get(handles.popupmenu1,'String');
switch str1{val1}
case 'string1'
if isempty(a) || isempty(b) || isempty(c)
warndlg('編輯框爲空!')
else
% 運行下面的代碼
end
case 'string2'
% 同上
end
看到過好幾個相似下面問題的帖子:
一、axes顯示圖片時隨着圖片的大小變化,如何固定axes顯示圖片大小;
二、當在axes使用subplot畫多個圖時,如何清空圖片,達到能夠重複繪製圖片的目的;昨天又遇到了http://www.ilovematlab.cn/thread-47629-1-1.html
動手作了一個例子驗證了一下,得出解決方法。
第一個問題很簡單,把axes放到一個panel面板中便可;
第二個問題稍微麻煩點,有人可能會說用cla/cla reset,這個時候cla/cla reset只能清除最後一個subplot對應的圖,其餘的不能清除,舉個例子說一下解決方法:%畫圖程序:
h1=subplot(121); %
記下句柄
h1
x=imread('football.jpg');
imshow(x);
h2=subplot(122); %
記下句柄
h2
y=imread('arms.jpg');
imshow(y);
%清空圖像
global h1 h2;
h=0;
if ishandle(h1) %
判斷
h1
是否是一個句柄
delete(h1);h=1;
end
if ishandle(h2) %
判斷
h2
是否是一個句柄
delete(h2);h=1;
end
if h
axes('parent',handles.uipanel1) %
重建一個
axes
end
我定義了一個global img=imread('x.bmp');一些處理img的程序。可是我退出界面程序時 再進入程序時img仍是最後處理後的圖像,怎麼在退出程序時把img清空呢?
clear all;
在GUI作了一個有三個座標軸的界面,用於顯示從串口接收到的數據。
串口設置以下:
g = serial('COM1') ;
g.InputBufferSize= 4096;
g.OutputBufferSize= 4000;
g.BaudRate= 9600;
g.BytesAvailableFcnMode = 'byte'; %中斷觸發事件爲’bytes-available Event’?
g.BytesAvailableFcnCount = 45; %接收緩衝區每收到45 個字節時, 觸發回調函數
g.BytesAvailableFcn = @instrcallback; %獲得回調函數句柄
回調函數instrcallback的繪製波形部分程序以下:
t =1:1:4;
axes(Ch1_Dis); %Ch1_Dis爲座標軸1句柄
hold on
plot(t,ch1);
axes(Ch2_Dis); %Ch2_Dis爲座標軸2句柄
hold on
plot(t,ch2);
axes(Ch3_Dis); %Ch3_Dis爲座標軸3句柄
hold on
plot(t,ch3);
可是每次經過串口觸發回調函數instrcallback時,執行到plot指令都會另建一窗口figure1,將波形繪製到另建的窗口中。
當我不經過串口觸發回調函數,而是在一按鈕的回調函數中調用instrcallback時,就會把波形繪製到指定座標軸中。
解決辦法:
將程序改成:
plot(t,ch1,'parent',Ch1_Dis);
plot(t,ch2,'parent',Ch2_Dis);
plot(t,ch3,'parent',Ch3_Dis);
但是我不明白爲何之前用axes設置當前座標軸不行,爲何在串口和定時器的回調函數中plot就不能在當前的座標軸中繪圖了,而用在其它函數就行!
問題的癥結所在:matlab自身的緣由
figure 的handlevisibility屬性設置的問題,缺省爲callback。要顯性地改成visibile。就能夠了。不然,在定時器或串口的回調函數裏繪圖都會出現這種狀況。
想作一個兩個GUI界面的鑲套 假如說 我創建一個GUI界面 繪製一個圖形 而後須要在這個GUI界面的菜單裏面加入一個按鈕 這個按鈕的做用是設置繪製這個圖形的參數 就須要再打開一個GUI界面和個人主界面進行關聯 請問這須要怎麼實現?
解決方法:
如下介紹幾種Callback之間最爲經常使用的數據傳遞方式:
1.宣告爲全域變量
將欲傳遞的變量在傳遞雙方的Callback位置中都設爲全域變量,就能夠在任一方的Callback中調用。
使用說明:global傳遞變量的方式爲當前有一組運算數據A必須在Tag名稱爲Pushbutton1與Pushbutton2所對應的對象Callback中使用,所以必須在雙方的Callback中都設置這個數據A爲全域變量。這樣經過全域變量的宣告,數據A就能夠跨越Pushbutton1與Pushbutton2這兩個Callback的變量了。
2.應用對象的UserData屬性
直接經過對象的UserData屬性來進行各個Callback之間的數據存取操做。首先必須先將數據存儲到一個特定的對象中,假設該對象的句柄值爲ui_handle,須要存儲的值爲Value,則輸入如下程序:
>>set('ui_handle','UserData','Value')
此時,Value數據就已經存儲在句柄值爲ui_handle的對象中,在執行過程當中若要取回該變量就能夠經過如下方式在任一Callback中獲取該數據值:
>>Value=get('ui_handle','UserData')
3.應用setappdata,getappdata,rmappdata函數
此種函數使用上很是相似上述的UserData,可是克服了它的缺點,使一個對象可以存取多個變量值,所以會比UserData屬性在操做上更具備彈性與數據安全性。
(1)setappdata
此函數可由定義的對象中得到特定的變量值,
value=getappdata(H,Name)
由定義的對象中得到變量名稱爲Name的值。其中H爲對象句柄值,若是該變量不存在,則matlab會返回一個空矩陣。
(2)getappdata
此函數可由定義的對象中創建一個變量值
setappdata(H,Name,value)
由定義的對象中創建一個變量名稱爲Name而內容爲value的值。其中H爲對象句柄值,若是該變量不存在,則matlab會自動設置Name與value。
(3)rmappdata
此函數用以移除定義對象中由setappdata指定的變量值,
rmappdata(H,Name)
移除定義的對象H中由serappdata指定的變量Name的值。
四、能夠經過workplace傳遞數據,使用assignin和evalin函數
函數說明以下:
ASSIGNIN Assign variable in workspace.
ASSIGNIN(WS,'name',V) assigns the variable 'name' in the
workspace WS the value V. WS can be one of 'caller' or 'base'.
EVALIN Evaluate expression in workspace.
EVALIN(WS,'expression') evaluates 'expression' in the context of
the workspace WS. WS can be 'caller' or 'base'. It is similar to EVAL
except that you can control which workspace the expression is
evaluated in.
[X,Y,Z,...] = EVALIN(WS,'expression') returns output arguments from
the expression.
舉個例子方便理解:
若是在figure1中有個變量a1
則傳入時assignin('base','a1',data) %data是workplace中的變量
在figure2傳出時a2=evalin('base','data'); %a2是figure2中的變量
引自王輝版主回覆的一個帖子:http://www.ilovematlab.cn/thread-56517-1-3.html
===========================================================
你看看這些帖子:
題目:(不一樣GUI之間控件的調用(原創))
論壇討論地址:
http://www.ilovematlab.cn/thread-52762-1-1.html
功能描述:
一、利用handles結構在控件之間傳遞數據。利用guihandles得到與傳入的句柄相關聯的handles結構,從而對不一樣GUI的控件進行操做。
二、 有兩個GUI: GUI1和GUI2,在GUI1中能夠操做GUI2的座標軸,繪製曲線;一樣,在GUI2中能夠操做GUI1的座標軸,繪製曲線。
三、在GUI1的edit中輸入數據,點擊按鈕,能夠在GUI2的edit中顯示出來;一樣,在GUI2的edit中輸入數據,點擊按鈕,能夠在GUI1的edit中顯示出來。
題目:利用GUI的輸入輸出參數實現不一樣GUI之間數據的傳遞
論壇討論地址:
http://www.ilovematlab.cn/thread-52846-1-1.html
功能描述:
有兩個GUI程序,GUI1和GUI2,在GUI1中調用一副圖片並顯示,而後點擊按鈕‘gui1->gui2’,在gui2中顯示該圖片。在gui2中完成圖片的剪切,並把剪切後的圖片在GUI1中顯示出來。
題目: Matlab多個窗口之間傳遞參數的問題
論壇討論地址:http://www.ilovematlab.cn/thread-52712-1-3.html
討論問題:對於多個GUI之間參數的傳遞的討論
最後結論: 該帖子對GUI之間參數的傳遞討論的很深刻。
題目:不一樣GUI之間控件的互相操做及數值的設定
論壇討論地址:http://www.ilovematlab.cn/thread-52762-1-5.html
實現功能描述:
一、利用handles結構在控件之間傳遞數據。利用guihandles得到與傳入的句柄相關聯的handles結構,從而對不一樣GUI的控件進行操做。
二、 有兩個GUI: GUI1和GUI2,在GUI1中能夠操做GUI2的座標軸,繪製曲線;一樣,在GUI2中能夠操做GUI1的座標軸,繪製曲線。
三、在GUI1的edit中輸入數據,點擊按鈕,能夠在GUI2的edit中顯示出來;一樣,在GUI2的edit中輸入數據,點擊按鈕,能夠在GUI1的edit中顯示出來。
題目: Matlab關於數據傳遞的一個要點
論壇討論地址:
http://www.ilovematlab.cn/thread-52917-1-7.html
討論問題:多個GUI之間進行數據傳遞的問題
題目:Matlab的GUI參數傳遞方式
論壇討論地址:
http://www.ilovematlab.cn/thread-46145-1-11.html
問題描述:
在gui設計中,常常會有gui內部控件之間,各個不一樣gui間的參數傳遞方式,所以對於參數傳遞方式的研究也是一個很熱門而由意義的話題。
最後結論:帖子中給出了七種參數傳遞的方式:
1) 運用gui自己的varain{}、varaout{}傳遞參數。2)運用global定義全局變量傳遞參數。
3)運用UserData傳遞參數。
4)應用setappdata\getappdata與rmappdata函數。5)結合handles和guidata函數。
6)運用save和load(importdata)。
7)共享變量訪問的方法 nested函數。
並分別說明了各類方法的使用範圍(gui內、外)和優劣。
假設有兩個GUI:GUI1和GUI2,它們之間怎麼互相調用和關閉?
解決方法:
假設在GUI1的按鈕的回調函數裏調用GUI2:
hGUI2=GUI2(); % hGUI2是GUI2對象的句柄
若想在GUI1中關閉GUI2,只須要代碼:
close(hGUI2);
這是顯示時間的一段定時器代碼,註釋是我本身寫的,但願大牛幫小弟看看。
t = timer('TimerFcn', {@timerCallback, handles.edit1}, 'ExecutionMode', 'fixedDelay', 'Period', 1.0);% 建立 timer 對象 TimerFcn表徵建立定時器回調函數,其句柄是timerCallback,同時向其傳遞參數handles.edit1,後面的很好理解,再也不贅述。
set(handles.figure1, 'DeleteFcn', {@DeleteFcn, t});% 設置figure1窗口關閉的回調函數其中'DeleteFcn'是刪除時間發生時的回調函數,其句柄是DeleteFcn,傳遞參數是t。
start(t); % 啓動定時器
function timerCallback(obj, event, hEdit) % timer 對象的回調函數-更新編輯框顯示的時間
set(hEdit, 'String', datestr(now, 'HH:MM:SS'));
function DeleteFcn(hObject, eventdata, t) % 窗口關閉的響應函數-中止計時器
stop(t);
以上是必定時器窗口,小弟想把其嵌入在個人GUI界面中,並增設開始結束按鍵。
在 openingFcn中增長如下代碼,創建定時器回調函數。
t = timer('TimerFcn', {@timerCallback, handles.edit1}, 'ExecutionMode', 'fixedDelay', 'Period', 1.0);
function timerCallback(obj, event, hEdit)
set(hEdit, 'String', datestr(now, 'HH:MM:SS'));
在 開始 案件 的回調函數中增長
start(handles.t);
在結束按鍵的回調函數中增長
stop(handles.t);
這是個人思路,但在運行中卻報錯 Error while evaluating uicontrol Callback.
解決方法:
t=timer('TimerFcn',{@timercallback,handles},'ExecutionMode', 'fixedDelay', 'Period', 1.0);
以上,定義定時器時,指定的傳入參數必需要與GUI傳遞的參數相符,GUI只會在各個callbacks之間傳遞它的handles (另外兩個忽略)。
因此一樣,timer的callback除了handles「要」不到別的東西。如下。
function timercallback(obj, event,handles)
set(handles.edit1, 'String', datestr(now, 'HH:MM:SS'));
有一個循環用來採集數據的,想加入一個waitbar而且在waitbar上加入按鈕,在取消的同時停止循環,不知怎麼能實現。
解決方法:
視頻版有一個GUI的視頻講了waitbar在循環中的使用,至於加取消能夠參考一下代碼。
stop=false;
h = waitbar(0.0,'Please wait...','CreateCancelBtn','stop=true; delete(h); clear h');
set(h,'Name','optional window name');
for i=1:1000
waitbar(i/1000,h,['Update ' num2str(i)]);
if stop break; end
% do stuff
end
if exist('h') delete(h); end
如何一次性讀入多張圖片,而且讓它們逐個處理好比像我上個問題所說的圖像分割,就是隻按一下button而後系統就自動逐個處理。而且在處理完了把這些圖像的名稱顯示在一個listbox中!
解決方法:
Matlab裏提供了很是方便的函數。
假如你的待處理圖片放在當前image文件夾裏,假設都是jpg格式,固然這些假設你能夠隨意改。
第一步: files = dir('test/*.jpg');
那麼files就含有全部圖片的屬性,咱們須要的只是圖片的name, 用來讀。
因此你就寫一個for loop
把每個圖片的name提取出來,而後調用你的程序就能夠了。
完整程序:
files = dir('test/*.jpg');
[row col]=size(files);
for j=1:row
im=imread(files(1,1).name); %讀
im2='你圖像處理程序' %處理 圖像
str=['E:\test\',num2str(j), '.bmp'];
imwrite(im2,str); %寫圖片
end;
把程序放到你的button callback裏就能夠,修改裏面的路徑。
想實現這樣的操做:這次輸入數據,經過保存按鈕做爲下一次打開時的初始化的數據。
解決方法:
這個是讀寫文件的問題,你能夠把數據保存在文件裏,而後每次打開GUI的時候,就讀這些文件。每次退出時,保存當前數據,覆蓋原來的文件。
具體問題:使用rectangle作矩形後,若是想用imwrite保存圖像,因爲沒有加入矩形的像素陣,沒法保存固然圖像狀態;若是想用save as來存儲figure窗口,每每會默認加入白邊,下面的代碼解決了這個問題,存儲效果較好。
這裏我也就很少說交互式做圖和設置figure窗口屬性的狀況了,只是強調一下如何能自動保存當前的gcf。
clc; close all; clear;
I = imread('westconcordaerial.png');
fg = figure;
set(fg, 'name', 'Viewer');
set(fg, 'NumberTitle', 'off');
old_units = get(fg, 'Units');
set(fg, 'Units', 'pixels');
figpos = get(fg, 'Position');
pos = get(fg, 'Position');
set(fg, 'Position', [pos(1) pos(2) size(I, 2) size(I, 1)]);
set(fg, 'Units', old_units);
old_units = get(gca, 'Units');
set(gca, 'Units', 'pixels');
set(gca, 'position', [0 0 size(I, 2) size(I, 1)]);
set(gca, 'Units', old_units);
imshow(I);
flag = 1; rectn = 0;
while flag == 1
[a, b, flag] = ginput(1);
if flag == 1
rectangle('position', [a - size(I, 1)/30, b - size(I, 2)/30,...
size(I, 1)/15, size(I, 2)/15],...
'LineWidth', 3, 'edgecolor', 'r');
rectn = rectn + 1;
end
end
str = sprintf('You Plot %d rectangle!', rectn);
helpdlg(str, 'report');
f = getframe(gca); %Capture screen shot
[im,map] = frame2im(f); %Return associated image data
if isempty(map) %Truecolor system
rgb = im;
else %Ind
exed system
rgb = ind2rgb(im,map); %Convert image data
end
str = sprintf('%drect.png', rectn);
imwrite(rgb, str);
(1)讀取數據
global chuizhifashetuilishuju;
global chuizhifashetuilixianshi;
[filename pathname]=uigetfile({'*.xls'},'Choose the file');
str=[pathname filename];
b=char([0 0]);
c=char(str);
if strcmp(b,c)
else
[INL,txt]=xlsread(str);
chuizhifashetuilishuju=INL;
chuizhifashetuilixianshi=str;
set(handles.chuizhifashetuilixianshi, 'String', str);
end
(2)寫入數據
我想把一個字符串寫入電子表格,格式以下:'第i組'. 我使用命令:i=2;suc=xlswrite('test_data',['第',num2str(i),'組'],'a1:a1'),結果在電子表格中只能看到一個字'第',如何可以在電子表格中顯示我想要的結果:'第2組'',。
解決辦法:
把代碼改爲以下形式:
i=2;
str=sprintf('第%d組 ',i);
suc=xlswrite('test_data',{str});
不要用[str],要用{str}。
或者:
問題的關鍵是,你的代碼輸出的是字符串,你要把原來的字符串,轉換爲元胞數組就能夠了。用mat2cell函數。
>> i=2;
>> data=['
第
',num2str(i),'
組
'];
>> d=mat2cell(data)
d =
'
第
2
組
'
>> suc=xlswrite('test_data',d,'sheet1', 'A1')
suc =
1
34-2
、在
excel
中連續輸入數據。
大致是經過GUI寫入exce數據,咱們常見的格式是:xlswrite('filename',M,sheet,'range')。我作了一個簡單的界面,也能夠將數據存入excle裏面,可是這種存入沒有連續性,只能存入特定的一行。由於在range方面,我不熟悉,書上給的例子是'A1:C1',也就是限制死了範圍,我但願能將1變成一個變量n,我每次點擊保存,變量n就自動的加1,可是試了幾回,關於變成變量n的格式不會掌握,因此格式總是錯誤。
另外我發現,若是寫入的excel先被打開的話,m文件是沒法運行的。只有把它關掉,才能夠運行,這個問題能解決嗎? [by makesure5]
function pushbutton1_Callback(hObject, eventdata, handles)%保存按鈕
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
number=get(handles.number,'string');
name= get(handles.name,'string');
sex= get(handles.sex,'string');
age = get(handles.age,'string');
data = {name,sex,age};
str=sprintf('A%s:C%s',number,number);
xlswrite('data.xls',data,str)
data1={'number','name','sex','age'};
data2={number,name,sex,age};
set(handles.uitable1,'data',data1);
set(handles.uitable1,'data',data2);
function pushbutton2_Callback(hObject, eventdata, handles)%重置按鈕
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.number,'string','');
set(handles.name,'string','');
set(handles.sex,'string','');
set(handles.age,'string','');
% --- Executes during object creation, after setting all properties.
function uitable1_CreateFcn(hObject, eventdata, handles)%uitable初始化
% hObject handle to uitable1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
data=[[],[],[],[]];
set(hObject,'data',data);
效果圖:
本人作了一4個button用於打開4個矩陣文件,第五個button用於把前四個button的數據寫到一個矩陣中去。本人想實現若只輸入前3個button的數據,第4個button不導入任何數據,如何實現第5個button能把前3個button的數據也寫到一個矩陣中去。如下是本人編的的條件語句,很差使啊!說明一下數據傳遞用的guidata型。
a=handles.a;
b=handles.b;
c=handles.c;
d=handles.d;
if isempty(d)
A=[a b c];
else
A=[a b c d];
解決方法:
首先在Openingfcn中初始化矩陣d爲空矩陣;
而後在各按鈕的回調函數中加入形如以下格式的語句:
handles.a=rand(3,3); % 隨機生成3*3矩陣作測試
guidata(hObject,handles);
最後在第5個按鈕的回調函數內加入以下代碼:
a=handles.a;
b=handles.b;
c=handles.c;
d=handles.d;
if isempty(d)
A=[a b c];
else
A=[a b c d];
end
當不按按鈕5時,d爲空矩陣,則輸出前三個矩陣;當按了按鈕5時,d被賦值,不爲空,則輸出a,b,c,d四個矩陣。
題目:編寫M函數統計十進制數值中"0"的個數,而後編寫腳本文件實現統計全部天然數1~2006中"0"的總個數。
方法1:
a=102030405;
b=num2str(a);
c=findstr('0',b);
n=length(c);
方法2:
clc; clear;
zero1 = 0; zero2 = 0;
for x = 1 : 2006
%
獲取字符串,兩種方式
str1 = num2str(x);
str2 = sprintf('%d', x);
%
獲取
0
個數
zeros1 = length(strfind(str1, '0'));
zeros2 = length(strfind(str2, '0'));
zero1 = zero1 + zeros1;
zero2 = zero2 + zeros2;
end
fprintf('\n Use num2str, the number is: %d\n', zero1);
fprintf('\n Use sprintf, the number is: %d\n', zero2);
若是不能,那麼想要達到這種效果應該怎麼辦?
問題說明:
在我設計的GUI界面中,我用菜單menu設回調函數在listbox裏打開1個名爲「Sample」的TXT, listbox內容以下: (第一項爲列表名字,第二項開始每項都是圖片名稱,格式爲「.jpg 」)
Test_Sample
Image1 Image1.jpg
Image2 Image2.jpg
Image3 Image3.jpg
Image4 Image4.jpg
Image5 Image5.jpg
Image6 Image6.jpg
Image7 Image7.jpg
Image8 Image8.jpg
Image9 Image9.jpg
Image10 Image10.jpg
程序以下:
fin=fopen('Sample.txt','r'); % 注:在工做路徑下
str=fgetl(fin);
[str1 ]=strread(str,'%s');
YangBen(1)=str1;
Counter=2;
global bianhao;
while feof(fin)==0
str=fgetl(fin);
[name bian]=strread(str,'%s %s','delimiter',' '); %name數組中存第一列,bian數組中存第二列
YangBen(Counter)=name;
bianhao(Counter-1)=bian;
Counter=Counter+1;
end;
set(handles.listbox1,'string',YangBen);
fclose(fin)
當我分別點擊「Image一、Image二、...Image10」時,想分別調用「Image1.jpg、Image2.jpg、...Image10.jpg」圖像即樣本圖像使其顯示在GUI界面(已插入一個axes)
請問這個程序該怎麼補充呢?
我本身在這個回調函數下function listbox1_Callback(hObject, eventdata, handles)添加了以下代碼:
global bianhao;
value=get(hObject,'value');
if(value==1)
vulue=1;
else
value=value-1;
end
a=bianhao(value);
ImageYePian=imread('a'); %讀彩色圖像
axes(handles.axes1);
imshow(ImageYePian);title('葉片原圖');
運行出現錯誤:
??? Error using ==> imread
File "a" does not exist.
在callback中用如下代碼便可實現:
key = get(handles.figure1,'CurrentKey'); % 取得當前按鍵的名稱,是return、space...
switch key
case 'a'
value=dec2hex(97);
hexvalue=sprintf('0x%s',value);
disp(hexvalue);
case 'b' .....................
end
或者:
key = eventdata.Key; % È¡µÃµ±Ç°°´¼üµÄÃû³Æ£¬ÊÇreturn¡¢space...
switch key
case 'space'
msgbox('你按下了空格鍵!!!!');
end
key的ASCII碼值參見ASCII碼錶。
39
、
GUI
如何響應鼠標事件
這些性質都是附屬於一個圖形視窗,所以,他們規範了在此圖形視窗
下,各項滑鼠事件的反應指令。
通常而言,咱們但願滑鼠先被按下,而後再移動滑鼠時,纔會觸發移
動時的反應指令.欲達到此效果,咱們必須作下列項:
l在滑鼠按鈕被按下時,設定 WindowButtonMotionFcn 及
WindowButtonUpFcn 的值.
l在滑鼠按鈕被釋放時,清除 WindowButtonMotionFcn 及
WindowButtonUpFcn 的值.
所以,只有在滑鼠按鈕被按下,且滑鼠在移動時,對應於
WindowButtonMotionFcn 的反應指令纔會被呼叫.
如下咱們用一個簡單的例子來講明.在這個例子中,滑鼠事件會產生
下列反應:
l按下滑鼠時,MATLAB 指令視窗會出現「Mouse down!」的
訊息.
l按下並移動滑鼠時,MATLAB 會在圖形視窗畫出滑鼠軌跡,並
指令視窗印出「Mouse is moving!」及當時滑鼠的位置.
l釋放滑鼠時,MATLAB 指令視窗會出現「Mouse up!」的訊息.
function tmouse(action)
% TMOUSE
本例展現如何以
Handle Graphics
來設定滑鼠事件
(Mouse
% Events)
的反應指令
(Callbacks)
if nargin == 0
action = 'start';
end
switch(action)
%
開啓圖形視窗
case 'start',
axis([0 1 0 1]);%
設定圖軸範圍
box on;%
將圖軸加上圖框
title('Click and drag your mouse in this window!');
%
設定滑鼠按鈕被按下時的反應指令爲「
tmouse down
」
set(gcf, 'WindowButtonDownFcn', 'tmouse down');
%
滑鼠按鈕被按下時的反應指令
case 'down',
%
設定滑鼠移動時的反應指令爲「
tmouse move
」
set(gcf, 'WindowButtonMotionFcn', 'tmouse move');
%
設定滑鼠按鈕被釋放時的反應指令爲「
tmouse up
」
set(gcf, 'WindowButtonUpFcn', 'tmouse up');
%
列印「
Mouse down!
」訊息
fprintf('Mouse down!\n');
%
滑鼠移動時的反應指令
case 'move',
currPt = get(gca, 'CurrentPoint');
x = currPt(1,1);
y = currPt(1,2);
line(x, y, 'marker', '.', 'EraseMode', 'xor');
%
列印「
Mouse is moving!
」訊息及滑鼠如今位置
fprintf('Mouse is moving! Current location = (%g, %g)\n', currPt(1,1), currPt(1,2));
%
滑鼠按鈕被釋放時的反應指令
case 'up',
%
清除滑鼠移動時的反應指令
set(gcf, 'WindowButtonMotionFcn', '');
%
清除滑鼠按鈕被釋放時的反應指令
set(gcf, 'WindowButtonUpFcn', '');
%
列印「
Mouse up!
」訊息
fprintf('Mouse up!\n');
end
要求利用MATLAB GUI設計實現圖像處理的圖形用戶界面,利用MATLAB圖像處理工具箱實現如下的圖像處理功能:
雙擊打開MATLAB 7.0→File→New→GUI→單擊 ,調整axes1大小→單擊OK,調整按鈕大小和顏色,修更名稱→再建axes2→單擊OK,調整按鈕大小和顏色,修更名稱→保存→View→M-file Edit→寫程序
1)圖像的讀取和保存。
在function open_Callback(hObject, eventdata, handles)後面輸入以下程序
[name,path]=uigetfile('*.*','');
file=[path,name];
axes(handles.axes1);
x=imread(file); %讀取圖像
handles.img=x;
guidata(hObject, handles);
imshow(x); %顯示圖像
title('打開');
在function save_Callback(hObject, eventdata, handles)後面輸入以下程序
[name,path]=uigetfile('*.*','');
file=[path,name];
axes(handles.axes1);
x=imread(file);
handles.img=x;
guidata(hObject, handles);
imshow(x);
imwrite(x,'new.jpg'); %保存圖像
title('保存');
2)設計圖形用戶界面,讓用戶可以對圖像進行任意的亮度和對比度變化調整,顯示和對比變換先後的圖像。
在function liangdu_Callback(hObject, eventdata, handles) 後面輸入以下程序
axes(handles.axes2);
x=(handles.img);
y=imadjust(x,[0.15 0.9], [0 1]); %增亮圖像
imshow(y);
title('亮度')
在function huidu_Callback(hObject, eventdata, handles) 後面輸入以下程序
axes(handles.axes2);
x=rgb2gray(handles.img); %RGB圖像轉換爲灰度圖像
imshow(x);
title('灰度')
3)設計圖形用戶界面,讓用戶可以用鼠標選取圖像感興趣區域,顯示和保存該選擇區域。
在function cut_Callback(hObject, eventdata, handles)後面輸入以下程序
axes(handles.axes2);
x=imcrop(handles.img); %截圖
imshow(x);
imwrite(x,'cut.jpg'); %保存圖像
title('截圖');
4)編寫程序經過最近鄰插值和雙線性插值等算法將用戶所選取的圖像區域進行放大和縮小整數倍的操做,並保存,比較幾種插值的效果。
在function nearfangda_Callback(hObject, eventdata, handles) 後面輸入以下程序
axes(handles.axes2);
x=imresize(handles.img,2,'nearest'); %最近鄰插值法放大
imshow(x);
imwrite(x,'nearfangda.jpg')
title('最近鄰插值法放大');
在function nearsuoxiao_Callback(hObject, eventdata, handles) 後面輸入以下程序
axes(handles.axes2);
x=imresize(handles.img,0.5,'nearest'); %最近鄰插值法縮小
imshow(x);
imwrite(x,'nearsuoxiao.jpg')
title('最近鄰插值法縮小');
在function doublefangda_Callback(hObject, eventdata, handles) 後面輸入以下程序
axes(handles.axes2);
x=imresize(handles.img,5,'bilinear'); %雙線性插值法放大圖像
imshow(x);
imwrite(x,'doublefangda.jpg');
title('雙線性插值法放大');
在function doublesuoxiao_Callback(hObject, eventdata, handles) 後面輸入以下程序
axes(handles.axes2);
x=imresize(handles.img,0.5,'bilinear'); %雙線性插值法縮小圖像
imshow(x);
imwrite(x,'doublesuoxiao.jpg');
title('雙線性插值法縮小');
5)圖像直方圖統計和直方圖均衡,要求顯示直方圖統計,比較直方圖均衡後的效果。
在function zhifangtu_Callback(hObject, eventdata, handles) 後面輸入以下程序
set(handles.axes2,'HandleVisibility','ON');
axes(handles.axes2);
x=imhist(handles.img); %直方圖統計
x1=x(1:10:256);
horz=1:10:256;
bar(horz,x1);
%axis([0 255 0 150000]);
set(handles.axes2,'xtick',0:50:255);
%set(handles.axes2,'ytick',0:2000:15000);
set(handles.axes2,'HandleVisibility','OFF');
在function junheng_Callback(hObject, eventdata, handles) 後面輸入以下程序
set(handles.axes2,'HandleVisibility','ON');
axes(handles.axes2);
h=histeq(handles.img); %直方圖均衡
imshow(h);
%set(handles.axes2,'ytick',0:2000:15000);
set(handles.axes2,'HandleVisibility','OFF');
6)能對圖像加入各類噪聲,並經過幾種濾波算法實現去噪並顯示結果。比較去噪效果。
在function gaussian_Callback(hObject, eventdata, handles) 後面輸入以下程序
axes(handles.axes2);
x=(handles.img);
y=imnoise(x,'gaussian',0,0.05); %加高斯噪聲
imshow(y);
imwrite(y,'gaussian.jpg');
title('加高斯噪聲')
在function salt_Callback(hObject, eventdata, handles) 後面輸入以下程序
axes(handles.axes2);
x=(handles.img);
y=imnoise(x,'salt & pepper',0.04); %加椒鹽噪聲
imshow(y);
imwrite(y,'salt.jpg');
title('加椒鹽噪聲')
在function medfilt_Callback(hObject, eventdata, handles) 後面輸入以下程序
axes(handles.axes2);
x=(handles.img);
y=imnoise(x,'salt & pepper',0.04); %加椒鹽噪聲
z=medfilt2(y,[5 5],'symmetric'); %中值濾波
imshow(z);
imwrite(z,'medfilt.jpg');
title('中值濾波');
在function wiener_Callback(hObject, eventdata, handles) 後面輸入以下程序
axes(handles.axes2);
x=(handles.img);
y=imnoise(x,'gaussian',0,0.05); %加高斯噪聲
z=wiener2(y,[5 5]); %自適應濾波
imshow(z);
imwrite(z,'wiener.jpg');
title('自適應濾波')
7)頻譜處理,可以分析圖像頻譜,顯示頻譜圖。
在function pinputu_Callback(hObject, eventdata, handles) 後面輸入以下程序
axes(handles.axes2);
x=(handles.img);
J2=fft2(x); %傅立葉變換
K2=fftshift(J2); %轉換數據矩陣
imshow(log(abs(K2)),[]); %顯示頻譜圖
title('頻譜圖');
8)設計巴特沃斯低通濾波對圖像進行低通濾波處理,顯示結果。
在function butterdi_Callback(hObject, eventdata, handles) 後面輸入以下程序
axes(handles.axes2);
x=(handles.img);
y1=imnoise(x,'salt & pepper'); % 疊加椒鹽噪聲
f=double(y1); % 數據類型轉換,MATLAB不支持圖像的無符號整型的計算
g=fft2(f); % 傅立葉變換
g=fftshift(g); % 轉換數據矩陣
[M,N]=size(g);
nn=2; % 二階巴特沃斯(Butterworth)低通濾波器
d0=50; %截止頻率爲50
m=fix(M/2); n=fix(N/2);
for i=1:M
for j=1:N
d=sqrt((i-m)^2+(j-n)^2);
h=1/(1+0.414*(d/d0)^(2*nn)); % 計算低通濾波器傳遞函數
result(i,j)=h*g(i,j);
end
end
result=ifftshift(result);
y2=ifft2(result);
y3=uint8(real(y2));
imshow(y3); % 顯示濾波處理後的圖像
imwrite(y3,'butterdi.jpg');
title('巴特沃斯低通濾波')
9)設計高斯高通慮波器,顯示結果。
axes(handles.axes2);
x=(handles.img);
y1=imnoise(x,'gaussian'); %加高斯噪聲
f=double(y1); % 數據類型轉換
k=fft2(f); % 傅立葉變換
g=fftshift(k); % 轉換數據矩陣
[M,N]=size(g);
nn=2;
d0=25; %截止頻率爲25
m=fix(M/2); n=fix(N/2);
for i=1:M
for j=1:N
d=sqrt((i-m)^2+(j-n)^2); % 計算高通濾波器傳遞函數
if d<=d0
h=0;
else h=1;
end
result(i,j)=h*g(i,j);
end
end
result=ifftshift(result);
y2=ifft2(result);
y3=uint8(real(y2));
imshow(y3); % 顯示濾波處理後的圖像
imwrite(y3,'gaussiangao.jpg');
title('高斯高通濾波')
版權聲明:轉載時請以超連接形式標明文章原始出處和做者信息及本聲明
http://liuxqsmile.blogbus.com/logs/17282262.html
MATLAB中提供了一些動態顯示圖形的例子,例如vibes、truss等,但他們的程序結構都和由GUIDE產生的M文件的結構不一樣。truss中用while循環來更新圖形窗口,pause函數來控制更新的速度。這樣的結構是不適合放在某一個子函數中來執行的,不然程序在執行該子函數時沒法響應用戶的其它操做,只能一開始就設置終止條件,等待動畫的天然結束。
MATLAB中的定時器timer能夠定時觸發,週期性地執行指定的函數,咱們能夠據此來實現繪圖的自動更新,而不會影響整個GUI對用戶其它操做的響應。
好比咱們要讓一個曲面隨時間週期性地變形,相似vibes中的情形,按下「開始」按鈕後,曲面開始週期振動,同時咱們能夠調整振幅大小、週期的長短。所不一樣的是咱們一切都在子函數中完成。
在GUIDE中創建界面元素後,在「開始」按鈕的callback中創建一個定時器timer對象object
handles.timer=timer(Period,0.05,ExecutionMode,FixedRate,... TimerFcn,{@PlotUpdate,handles});
Period是觸發的週期,這裏設置爲0.05s,ExecutionMode是執行的方式,能夠有三種選擇,對於不須要精確控制時序的動畫的影響不大,TimerFcn指定觸發時所執行函數的句柄,在這裏咱們創建一個函數PlotUpdate來執行繪圖命令,handles做爲參數傳遞到PlotUpdate中去。
注意PlotUpdate的定義:
function PlotUpdate(obj,events,handles)
前兩個參數是必不可少的,最後的handles纔是用戶傳遞的數據。在這個函數中你基本上能夠無視前兩個參數,按照曲面的運動趨勢產生新的頂點座標,而後用set命令將新的座標賦給曲面(面片patch)對象的Vertices屬性。drawnow更新就能夠了。你能夠用曲面對象的UserData屬性存放當前振動的幅值相位等參數。
而後在「中止」按鈕的callback中st(handles.timer)中止定時器,就能夠中止自動繪圖了。
在「增大振幅」按鈕的callback中對振幅參數做修改。排除了一些小問題後,你的曲面終於能夠動起來了,按「增大振幅」等也沒有影響圖形的運動,真的是「一點影響都沒有」啊!
問題出在哪裏呢?原來,當定時器第一次觸發時,用戶指定的參數被傳遞到響應函數中執行,之後每一次觸發,都是使用的這同一組參數,並不會隨着程序的運行而更新。好了,如今能夠在「增大振幅」中從新賦一次參數
set(handles.timer,TimerFcn,{@PlotUpdate,handles});
版權聲明:轉載時請以超連接形式標明文章原始出處和做者信息及本聲明
http://liuxqsmile.blogbus.com/logs/17282259.html
在研學論壇上看到有人問這個問題,把方法在這裏從新貼一下:
在GUI子程序的OpeningFcn函數的結尾加上uiwait(handles.figure1); figure1是子GUI的Tag;
子GUI中控制程序結束(如"OK」和"Cancel"按鈕)的callback末尾加上uiresume(handles.figure1),不要將delete命令放在這些callback中;
在子GUI的OutputFcn中設置要傳遞出去的參數,如 varargout{1} = handles.par1;varargout{2} = handles.par2;末尾添加 delete(handles.figure1); 結束程序。
在GUI的OpenFcn中,若是不加uiwait, 程序會直接運行到下面,執行OutputFcn。也就是說程序一運行,返回值就肯定了,再在其它部分對handles.output做更改也沒有效果了。加上uiwait後,只有執行了uiresume後,纔會繼續執行到OutputFcn,在此以前用戶有充分的時間設置返回值。在一個GUI中調用另外一個GUI時,主GUI不須要特別的設置,同調用普通的函數同樣。在打開子GUI界面的同時,主程序還能夠響應其它的控件。不須要擔憂子GUI的返回值被傳錯了地方。
版權聲明:轉載時請以超連接形式標明文章原始出處和做者信息及本聲明
http://liuxqsmile.blogbus.com/logs/17622732.html
MATLAB 中GUI子程序的參數傳遞
輸入參數傳遞:
好比子GUI的名稱爲subGUI, 設想的參數輸入輸出爲:[out1, out2] = subGUI(in1, in2)
在subGUI的m文件中(由GUIDE自動產生):
1.第一行的形式爲:function varargout = subGUI(varargin)
該行不用作任何修改;varargin 和 varargout 分別是一個可變長度的cell數組(MATLAB幫助文件中有說明)。輸入參數in1和in2保存在varargin中,輸出參數out1,out2包含在varargout中;
2.在subGUI的OpeningFcn中,讀入參數,並用guidata保存,即:
handles.in1 = varargin{1};
handles.in2 = varargin{2};
guidata(hObject, handles);
返回參數的設置:
1. 在GUI子程序的OpeningFcn函數的結尾加上uiwait(handles.figure1); figure1是subGUI的Tag;
2. subGUI中控制程序結束(如"OK」和"Cancel"按鈕)的callback末尾加上uiresume(handles.figure1),不要將delete命令放在這些callback中;
3. 在子GUI的OutputFcn中設置要傳遞出去的參數,如 varargout{1} = handles.out1;varargout{2} = handles.out2;末尾添加 delete(handles.figure1); 結束程序。
在GUI的OpenFcn中,若是不加uiwait, 程序會直接運行到下面,執行OutputFcn。也就是說程序一運行,返回值就肯定了,再在其它部分對handles.output做更改也沒有效果了。
加上uiwait後,只有執行了uiresume後,纔會繼續執行到OutputFcn,在此以前用戶有充分的時間設置返回值。
經過以上設置之後,就能夠經過 [out1, out2] = subGUI(in1, in2) 的形式調用該子程序。
在一個GUI中調用另外一個GUI時,主GUI不須要特別的設置,同調用普通的函數同樣。在打開子GUI界面的同時,主程序還能夠響應其它的控件。不須要擔憂子GUI的返回值被傳錯了地方。
作了一個按鈕「保存」,能夠另存爲畫在axes上的圖,保存爲jpg格式,參考了論壇裏的帖子,寫了代碼,但是保存的圖片是空的,什麼都沒有,請問是哪裏的問題?保存的圖片如何才能包括axes的座標軸?
function m_file_save1_Callback(hObject, eventdata, handles)
% hObject handle to m_file_save1 (see GCBO)
% eventdata reserved - to be defined in a future version of
MATLAB% handles structure with handles and user data (see
GUIDATA)
axes(handles.axes1); %
取得
axes
1的句柄
if isempty(handles.axes1)
return;
end
newFig =
figure;%
因爲直接保存
axes1
上的
圖像有困難,因此保存在新建的
figure
中的譜圖
set(newFig,'Visible','off')%
設置新建的
figure
爲不可見
newAxes = copyobj(handles.axes1,newFig); %
將
axes1
中的圖複製到新建的
figure
中
set(newAxes,'Units','default','Position','default'); %
設置圖顯示的位置
[filename,pathname] = uiputfile({ '*.jpg','figure type(*.jpg)'}, '
保存原始波形
');
if isequal(filename,0)||isequal(pathname,0)%
若是用戶選擇
「
取消
」
,則退出
return;
else
fpath=fullfile(pathname,filename);
end
imwrite(newFig,fpath);%
保存圖片
問題解決:
你提出的問題頗有特色,可是代碼中imwrite寫出的是figure德handle,按理說是應該沒有圖像的;
你能夠採用:
f = getframe(gcf);
f = frame2im(f);
imwrite(f, fpath);
axes(handles.axes1); %
取得
axes
1的句柄
if isempty(handles.axes1)
return;
end
newFig = figure;%
因爲直接保存
axes1
上的圖像有困難,因此保存在新建的
figure
中的譜圖
set(newFig,'Visible','off')%
設置新建的
figure
爲不可見
newAxes = copyobj(handles.axes1,newFig); %
將
axes1
中的圖複製到新建的
figure
中
set(newAxes,'Units','default','Position','default'); %
設置圖顯示的位置
[filename,pathname] = uiputfile({ '*.jpg','figure type(*.jpg)'}, '
保存原始波形
');
if isequal(filename,0)||isequal(pathname,0)%
若是用戶選擇
「
取消
」
,則退出
return;
else
fpath=fullfile(pathname,filename);
end
%imwrite(newFig,fpath);%
若是用戶選擇
「
取消
」
,則退出
f = getframe(gcf);
f = frame2im(f);
imwrite(f, fpath);
不知道這樣改對不對,能不能幫忙修改一下?
是否該這樣:
f = getframe(newFig);
f = frame2im(f);
imwrite(f, fpath);
這樣就能夠了,謝了!
相信你們都知道,MATLAB提供了一種很是方便的控制方式,利用ButtonDownFcn並配合Figure對象所提供的WindowButtonDownFcn(控制當鼠標有按鍵被單擊時所執行的操做)、 WindowButtonMotionFcn ( 控制鼠標移動時所執行的操做)、 WindowButtonUpFcn(控制當鼠標被釋放時所執行的操做),來完成鼠標控制的工做,下面給你們兩個運用這些命令的小例子,以供你們參考!
1.WindowButtonDownFcn
當用戶用鼠標在空白處點擊時,出現歡迎對話框
>> uicontrol(h,'style','text','position',[80,100,100,20],'string','
請在空白處單擊一下
')
>> h=
figure ('color',[1 1 0],'position',[400 300 200 200],...
'name','Demo','menu','figure','WindowButtonDownFcn',...
'msgbox(''
歡迎光臨
MATLAB
中文論壇
'',''Window Message'',''help'')');
>> uicontrol(h,'style','text','position',[80,100,100,20],'string',...
'
請任意單擊一下
')
啓動界面:
單擊鼠標後的界面:
2.綜合例子---實現畫筆功能程序代碼1
function mouse(action)
switch action
case 'start'
%
當光標移動時
執行
'move'
的操做
set(gcbf,'windowbuttonmotionfcn','mouse move');
%
當光標移動時
執行
'stop'
的操做
set(gcbf,'windowbuttonupfcn','mouse stop');
case 'move'
%
得到當前鼠標的
座標point = get(gca,'CurrentPoint');
%
畫出
X
與
Y
得座標值
line(point(:,1),point(:,2),'clipping','on',...
'erasemode','background','marker','o');
case 'stop' %
當鼠標鍵被釋放時,不執行任何操做
set(gcbf,'windowbuttonmotionfcn','');
set(gcbf,'windowbuttonupfcn','');
end
代碼2
function varargout = matlab(varargin)
% MATLAB M-file for matlab.fig
% MATLAB, by itself, creates a new MATLAB or raises the existing
% singleton*.
%
% H = MATLAB returns the handle to a new MATLAB or the handle to
% the existing singleton*.
%
% MATLAB('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in MATLAB.M with the given input arguments.
%
% MATLAB('Property','Value',...) creates a new MATLAB or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the
GUI before painter_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to matlab_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Copyright 2002-2003 The MathWorks, Inc.
% Edit the above text to modify the response to help matlab
% Last Modified by GUIDE v2.5 03-Oct-2009 17:01:36
% Begin initialization code - DO NOT
EDITgui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @matlab_OpeningFcn, ...
'gui_OutputFcn', @matlab_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before matlab is made visible.
function matlab_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to matlab (see VARARGIN)
% Choose default command line output for matlab
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes matlab wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.function varargout = matlab_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on mouse press over
axes background.
function axes1_ButtonDownFcn(hObject, eventdata, handles)
% hObject handle to axes1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
mouse start
步驟是須要利用GUIDE添加一個Static和一個 Text Axes,而後添加Callback函數便可,便可實現以下的畫筆功能。
function varargout = zhenghui(varargin)
% ZHENGHUI M-file for zhenghui.fig
% ZHENGHUI, by itself, creates a new ZHENGHUI or raises the existing
% singleton*.
%
% H = ZHENGHUI returns the handle to a new ZHENGHUI or the handle to
% the existing singleton*.
%
% ZHENGHUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in ZHENGHUI.M with the given input arguments.
%
% ZHENGHUI('Property','Value',...) creates a new ZHENGHUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before zhenghui_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to zhenghui_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help zhenghui
% Last Modified by GUIDE v2.5 04-Oct-2009 15:46:38
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @zhenghui_OpeningFcn, ...
'gui_OutputFcn', @zhenghui_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before zhenghui is made visible.
function zhenghui_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to zhenghui (see VARARGIN)
% Choose default command line output for zhenghui
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes zhenghui wait for user response (see UIRESUME)
% uiwait(handles.figure1);
%
建立繪圖數據源
%
定義三維繪圖數據源
handles.peaks=peaks;
handles.membrane=membrane;
[x,y]=meshgrid(-8:.5:8);
r=sqrt(x.^2+y.^2)+eps;
sinc=sin(r)./r;
handles.sinc = sinc;
%
定義二維繪圖數據源
f=@(x,y) 3*(1-x).^2.*exp(-(x.^2) - (y+1).^2) ...
- 10*(x/5 - x.^3 - y.^5).*exp(-x.^2-y.^2) ...
- 1/3*exp(-(x+1).^2 - y.^2);
handles.ezcontour=f;
handles.ezplot='x^2-y^4';
handles.ezpolar='1+cos(t)';
%
初始化繪圖函數
handles.currentdata=handles.ezplot;
ezplot(handles.currentdata);
%
選擇
2-D
set(findobj(gcf,'tag','radiobutton1'),'Value',1);
%
保存
handles
結構對象
guidata(hObject, handles);
% --- Outputs from this function are returned to the command line.
function varargout = zhenghui_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close;
% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns popupmenu1 contents as cell array
% contents{get(hObject,'Value')} returns selected item from popupmenu1
val=get(hObject,'Value');
str=get(hObject,'String');
switch str{val}
case 'peaks'
handles.currentdata=handles.peaks;
case 'membrane'
handles.currentdata=handles.membrane;
case 'sinc'
handles.currentdata=handles.sinc;
end
guidata(hObject,handles);
listbox1_Callback(handles.listbox1,[], handles)
;
% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject handle to popupmenu1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in radiobutton1.
function radiobutton1_Callback(hObject, eventdata, handles)
% hObject handle to radiobutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of radiobutton1
%
把
radiobutton2
清零
set(findobj(gcf,'Tag','radiobutton2'),'Value',0);
%
設置列表框的
string
屬性
set(findobj(gcf,'Tag','listbox1'),'String',{'ezplot','ezcontour','ezpolar'});
%
下拉菜單框使能狀態改爲
off
set(findobj(gcf,'Tag','popupmenu1'),'Enable','off');
%
注意這裏改變了繪圖類型並不進行繪圖操做
% --- Executes on button press in radiobutton2.
function radiobutton2_Callback(hObject, eventdata, handles)
% hObject handle to radiobutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of radiobutton2
%
把
radiobutton1
清零
set(findobj(gcf,'Tag','radiobutton1'),'Value',0);
%
設置列表框的
string
屬性
set(findobj(gcf,'Tag','listbox1'),'String',{'surf','mesh','surfc'});
%
下拉菜單框使能狀態改爲
on
set(findobj(gcf,'Tag','popupmenu1'),'Enable','on','Value',1);
%
注意這裏改變了繪圖類型並不進行繪圖操做
%
改變三維繪圖數據默認爲
peaks
handles.currentdata=handles.peaks;
guidata(hObject,handles);
% --- Executes on selection change in listbox1.
function listbox1_Callback(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = get(hObject,'String') returns listbox1 contents as cell array
% contents{get(hObject,'Value')} returns selected item from listbox1
val=get(hObject,'Value');
str=get(hObject,'String');
%
強制讓檢錄況選上
set(findobj(gcf,'Tag','checkbox1'),'Value',1);
switch str{val}
case 'ezplot'
handles.currentdata=handles.ezplot;
ezplot(handles.currentdata)
case 'ezcontour'
handles.currentdata=handles.ezcontour;
ezcontour(handles.currentdata,[-3,3],49)
case 'ezpolar'
handles.currentdata=handles.ezpolar;
ezpolar(handles.currentdata)
case 'surf'
surf(handles.currentdata);
case 'mesh'
mesh(handles.currentdata);
case 'surfc'
surfc(handles.currentdata);
end
%
判斷是否添加標題函數
str = get(findobj(gcf,'Tag','edit1'),'String');
if length(str)>0
title(str);
end;
guidata(hObject,handles);
% --- Executes during object creation, after setting all properties.
function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes during object creation, after setting all properties.
function listbox2_CreateFcn(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function edit1_Callback(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit1 as text
% str2double(get(hObject,'String')) returns contents of edit1 as a double
% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in checkbox1.
function checkbox1_Callback(hObject, eventdata, handles)
% hObject handle to checkbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
val=get(hObject,'Value');
if(val)
axis on;
else
axis off;
end
% Hint: get(hObject,'Value') returns toggle state of checkbox1
% --- Executes during object creation, after setting all properties.
function axes1_CreateFcn(hObject, eventdata, handles)
% hObject handle to axes1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: place code in OpeningFcn to populate axes1
% --- Executes during object creation, after setting all properties.
function uipanel2_CreateFcn(hObject, eventdata, handles)
% hObject handle to uipanel2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
1.
handles.peaks=peaks;%將函數z = 3*(1-x).^2.*exp(-(x.^2) - (y+1).^2) ...
- 10*(x/5 - x.^3 - y.^5).*exp(-x.^2-y.^2) ...
- 1/3*exp(-(x+1).^2 - y.^2)賦值給全局變量
handles.membrane=membrane; %建立MATLAB logo圖形
[x,y]=meshgrid(-8:.5:8); %將XY向量展開爲矩陣平面
r=sqrt(x.^2+y.^2)+eps; %產生非零的函數
sinc=sin(r)./r; %sinc函數
handles.sinc = sinc; %保存到全局變量
% 定義二維繪圖數據源
f=@(x,y) 3*(1-x).^2.*exp(-(x.^2) - (y+1).^2) ...
- 10*(x/5 - x.^3 - y.^5).*exp(-x.^2-y.^2) ...
- 1/3*exp(-(x+1).^2 - y.^2);
handles.ezcontour=f;
handles.ezplot='x^2-y^4';
handles.ezpolar='1+cos(t)';
% 初始化繪圖函數
handles.currentdata=handles.ezplot;
ezplot(handles.currentdata); %實際上就是 ezplot('x^2-y^4'),畫圖。
% 選擇2-D 若是沒有這一句,運行開始時,兩個radiobutton都處於不選中的狀態
set(findobj(gcf,'tag','radiobutton1'),'Value',1);
% 保存handles結構對象
guidata(hObject, handles); %更新數據 這一句是很是重要的,必定不要忘了寫,不然會發生錯誤!
2.
下面這段程序有點基礎的都能看懂吧!不懂得回帖問!
關鍵是get findobj set函數的運用,都是很基本的函數,也會死GUI必須掌握的函數!
radiobutton1
% 把radiobutton2清零
set(findobj(gcf,'Tag','radiobutton2'),'Value',0);
% 設置列表框的string屬性
set(findobj(gcf,'Tag','listbox1'),'String',{'ezplot','ezcontour','ezpolar'});
% 下拉菜單框使能狀態改爲off
set(findobj(gcf,'Tag','popupmenu1'),'Enable','off');
% 注意這裏改變了繪圖類型並不進行繪圖操做
3.解釋一下switch str{val}的含義:
str是popup中全部字符串組成的元胞數組,用{}來表示,與矩陣類似,可是每一個元素的字符串長度能夠不一樣。val是對應選擇的下拉才當的序號,分別爲1,2,3.
str{val}就是表示當前選中項的字符串。舉例:當你點擊peakst時,val=1,str{val}=peaks.(感謝hyowinner版主)
val=get(hObject,'Value');
str=get(hObject,'String');
%強制讓檢錄況選上
set(findobj(gcf,'Tag','checkbox1'),'Value',1);
switch str{val}
case 'ezplot'
handles.currentdata=handles.ezplot;
ezplot(handles.currentdata)
case 'ezcontour'
handles.currentdata=handles.ezcontour;
ezcontour(handles.currentdata,[-3,3],49)
case 'ezpolar'
handles.currentdata=handles.ezpolar;
ezpolar(handles.currentdata)
case 'surf'
surf(handles.currentdata);
case 'mesh'
mesh(handles.currentdata);
case 'surfc'
surfc(handles.currentdata);
end
% 判斷是否添加標題函數
str = get(findobj(gcf,'Tag','edit1'),'String');
if length(str)>0
title(str);
end;
guidata(hObject,handles);
4.
定義座標軸是否顯示
val=get(hObject,'Value');
if(val)
axis on;
else
axis off;
end
最終效果圖
啓動界面:
MATLAB軟件的logo
清除axes畫面
axes(handles.axes1);imshow([255]);
清除掉,怎麼保留AXES本來外框線,讓他還留著
解決辦法:
axes(handles.axes1);imshow([255]);
axis on;
ax_handles1=handles.axes1;
set(ax_handles1,'XTickLabel',[])
set(ax_handles1,'YTickLabel',[])
set(ax_handles1,'XTick',[])
set(ax_handles1,'YTick',[])
The GUI Help Button
The GUI Help button callback displays an HTML file in the MATLAB Help browser. It uses two commands:
The which command returns the full path to the file when it is on the MATLAB path
the web command displays the file in the Help browser.
This is the Help button callback.
function HelpButton_Callback(hObject, eventdata, handles)
HelpPath = which('f14ex_help.html');
web(HelpPath);
我這裏有一個例子,不知道能不能幫上你,我是在m文件裏設置參數,而後調用simulink 模型,本質上應該跟GUI是同樣的。
它的流程是這樣的:
你讓你的simulink模型參數,選自來自workspace(工做區域)
用你的gui函數,更新workspace的參數,而後調用simulink模型,就能夠了。看一個例子:
K=2;%參數名(就是模型裏的gain)
simopt = simset('SrcWorkspace','Current');%告訴simulink, 用當前workspace裏的參數
% 調用模型,而且返回模型運行結果
[tout,xout,yout] = sim('multiply',[1 1],simopt);
見callmodel例子。
function KfCurrentValue_Callback(hObject, eventdata, handles)
% Ensure model is open
model_open(handles)
% Get the new value for the Kf Gain
NewStrVal = get(hObject, 'String');
NewVal = str2double(NewStrVal);
% Check that the entered value falls within the allowable range
if isempty(NewVal) | (NewVal< -5) | (NewVal>0),
% Revert to last value, as indicated by KfValueSlider
OldVal = get(handles.KfValueSlider,'Value');
set(hObject, 'String',OldVal)
else, % Use new Kf value
% Set the value of the KfValueSlider to the new value
set(handles.KfValueSlider,'Value',NewVal)
% Set the Gain parameter of the Kf Gain Block to the new value
set_param('f14/Controller/Gain','Gain',NewStrVal)
end
function SimulateButton_Callback(hObject, eventdata, handles)
[timeVector,stateVector,outputVector] = sim('f14');
% Retrieve old results data structure
if isfield(handles,'ResultsData') &
~isempty(handles.ResultsData)
ResultsData = handles.ResultsData;
% Determine the maximum run number currently used.
maxNum = ResultsData(length(ResultsData)).RunNumber;
ResultNum = maxNum+1;
else
% Set up the results data structure
ResultsData = struct('RunName',[],'RunNumber',[],...
'KiValue',[],'KfValue',[],'timeVector',[],...
'outputVector',[]);
ResultNum = 1;
end
if isequal(ResultNum,1),
% Enable the Plot and Remove buttons
set([handles.RemoveButton,handles.PlotButton],'Enable','on')
end
% Get Ki and Kf values to store with the data and put in the
results list.
Ki = get(handles.KiValueSlider,'Value');
Kf = get(handles.KfValueSlider,'Value');
ResultsData(ResultNum).RunName = ['Run',num2str(ResultNum)];
ResultsData(ResultNum).RunNumber = ResultNum;
ResultsData(ResultNum).KiValue = Ki;
ResultsData(ResultNum).KfValue = Kf;
ResultsData(ResultNum).timeVector = timeVector;
ResultsData(ResultNum).outputVector = outputVector;
% Build the new results list string for the listbox
ResultsStr = get(handles.ResultsList,'String');
if isequal(ResultNum,1)
ResultsStr = {['Run1',num2str(Kf),' ',num2str(Ki)]};
else
ResultsStr = [ResultsStr;...
{['Run',num2str(ResultNum),' ',num2str(Kf),' ', ...
num2str(Ki)]}];
end
set(handles.ResultsList,'String',ResultsStr);
% Store the new ResultsData
handles.ResultsData = ResultsData;
guidata(hObject, handles)
菜單中退出項的回調函數能夠以下:
function Untitled_10_Callback(hObject, eventdata, handles)
% hObject handle to Untitled_10 (see GCBO)
% eventdata reserved - to be defined in a future version of
MATLAB% handles structure with handles and user data (see
GUIDATA)
selection = questdlg('Close This Figure?',...
'Close Request Function',...
'Yes','No','Yes');
switch selection,
case 'Yes',
delete(gcf)
case 'No'
return
end
至於窗口關閉能夠以下:
function test %
確認關閉右上腳的關閉按鈕
figure;
set(gcf,'CloseRequestFcn',@my_closefcn);
function my_closefcn(src,evnt)
% User-defined close request function
% to display a question dialog box
selection = questdlg('Close This Figure?',...
'Close Request Function',...
'Yes','No','Yes');
switch selection,
case 'Yes',
delete(gcf)
case 'No'
return
end
如今考慮如何能將二者合二爲一?
參數含義:
前者三個參數:
hObject------hObject handle to Untitled_10 (see GCBO);
eventdata ------reserved,to be defined in a future version of MATLAB;
handles------ handles structure with handles and user data (see GUIDATA)。
後者兩個參數:
src------The handle of the object generating the callback (the source of the event) 理解同hObject;
event------The event data structure (can be empty for some callbacks)理解同eventdata;
若是寫出以下語句set(gcf,'CloseRequestFcn',………
@Untitled_10_Callback);關閉窗口會發現報錯以下:
??? Input argument "handles" is undefined.意思就是handles未定義,由於@my_function默認只有兩個參數。可考慮按以下擴展一個參數:
set(gcf,'CloseRequestFcn',{@Untitled_10_Callback,handles});
function CalendarTable
% calendar ÈÕÀú
% Example:
% CalendarTable;
S=datestr(now);
[y,m,d]=datevec(S);
% d is day
% m is month
% y is year
DD={'Sun','Mon','Tue','Wed','Thu','Fri','Sat'};
close all
figure;
for k=1:7;
uicontrol(gcf,'style','text',... 'unit','normalized','position',[0.02+k*0.1,0.55,0.08,0.06],... 'BackgroundColor',0.6*[1,1,1],'ForegroundColor','b',...
'String',DD(k),'fontsize',16,'fontname','times new Roman');
end
h=1;
ss='b';
qq=eomday(y,m);
for k=1:qq;
n=datenum(y,m,k);
[da,w] = weekday(n);
if k==d;
ss='r';
end
uicontrol(gcf,'style','push',...
'unit','normalized','position',[0.02+da*0.1,0.55-h*0.08,0.08,0.06],...
'BackgroundColor',0.6*[1,1,1],'ForegroundColor',ss,...
'String',num2str(k));
ss='b';
if da==7;
h=h+1;
end
end
uicontrol(gcf,'style','push',...
'unit','normalized','position',[0.6,0.66,0.12,0.08],...
'BackgroundColor',0.6*[1,1,1],'ForegroundColor',ss,...
'String','clock','fontsize',18,'fontname','times new roman');
Tq=uicontrol(gcf,'style','push',...
'unit','normalized','position',[0.74,0.66,0.17,0.08],...
'BackgroundColor',0.6*[1,1,1],'ForegroundColor',[0.1,0.9,0.9],...
'fontsize',18,'fontname','times new roman');
sq='The calendar';
uicontrol(gcf,'style','push',...
'unit','normalized','position',[0.14,0.86,0.37,0.08],...
'BackgroundColor',0.6*[1,1,1],'ForegroundColor',[0.1,0.9,0.9],...
'fontsize',18,'fontname','times new roman','string',sq);
try
while 1
set(Tq,'String',datestr(now,13));
pause(1);
end
end
這個叫作「Using Multiple X- and Y-Axes」
若是隻是想雙Y:使用plotyy, 例如:
t = 0:900; A = 1000; a = 0.005; b = 0.005;
z1 = A*exp(-a*t);
z2 = sin(b*t);
[haxes,hline1,hline2] = plotyy(t,z1,t,z2,'semilogy','plot');
開發動態GUI是一件比較有挑戰性的工做。
首先說明一下,什麼是動態GUI: 就是說你的程序, 根據用戶選擇的不一樣,要產生相應的GUI, 舉個簡單例子,用戶選了3x3,那麼你的gui界面上,就要出現3x3的編輯框。
好比說,上傳我在開發「Matlab實現層次分析法」的時候(以下圖),用的是GUIDE開發的,沒有直接單靠寫代碼(人比較懶),一開始開發的時候,比較容易。後來牽涉到動態的時候,就很麻煩,由於用戶頗有可能選擇一個10x10的編輯框, 那麼,若是手動開發一個10*10的編輯框,是一件多麼痛苦的事情啊(本科時候,我這樣作過,當時作sliding mode control, 須要輸入不少參數,根據用戶的須要,而後決定讓某些編輯框顯示或者隱藏,這個Matlab實現層次分析法也是,這樣很差), 因此了, 我建議你們,遇到這樣的狀況,須要開發動態的GUI, 用代碼來幫你生成GUI
若是你對寫動態gui有什麼心得,或者什麼經驗,咱們不妨討論一下,看看什麼樣的代碼或者方法,能夠生成最適合用戶須要的動態GUI.歡迎跟帖討論。
見實例程序:dynamicgui.m
利用GUI執行Simulink模塊時遇到了難題,想找一些GUI執行SIMULINK方面的資料,就是利用GUI設置simulink模塊的參數,而且用GUI的按鈕來執行Simulink的仿真運行!其中GUI設置Simulink參數部分在matlab help文件的gui application下的實例中可以比較容易的掌握和理解,可是關於GUI的按鈕回調函數下面的代碼,特別是新建的一個結構體變量,真是一點看不懂!
附上按鈕回調函數的代碼,藍色代碼即小弟的困惑,但願大俠們指點一二,也歡迎和我同樣對GUI感興趣並正在HELP文件裏摸索的朋友們一塊兒學習交流!
%---------------------------------------------------------
% Callback for the Simulate and store results button
% ---------------------------------------------------------
function varargout = SimulateButton_Callback(h, eventdata, handles)
% hObject handle to SimulateButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[timeVector,stateVector,outputVector] = sim('f14');
% Retrieve old results data structure
if isfield(handles,'ResultsData') & ~isempty(handles.ResultsData)
ResultsData = handles.ResultsData;
% Determine the maximum run number currently used.
maxNum = ResultsData(length(ResultsData)).RunNumber;
ResultNum = maxNum+1;
else, % Set up the results data structure
ResultsData = struct('RunName',[],'RunNumber',[],...
'KiValue',[],'KfValue',[],'timeVector',[],'outputVector',[]);
ResultNum = 1;
end
if isequal(ResultNum,1),
%--Enable the Plot and Remove buttons
set([handles.RemoveButton,handles.PlotButton],'Enable','on')
end
% Get Ki and Kf values to store with the data and put in the results list.
Ki = get(handles.KiValueSlider,'Value');
Kf = get(handles.KfValueSlider,'Value');
ResultsData(ResultNum).RunName = ['Run',num2str(ResultNum)];
ResultsData(ResultNum).RunNumber = ResultNum;
ResultsData(ResultNum).KiValue = Ki;
ResultsData(ResultNum).KfValue = Kf;
ResultsData(ResultNum).timeVector = timeVector;
ResultsData(ResultNum).outputVector = outputVector;
% Build the new results list string for the listbox
ResultsStr = get(handles.ResultsList,'String');
if isequal(ResultNum,1)
ResultsStr = {['Run1 ',num2str(Kf),' ',num2str(Ki)]};
else
ResultsStr = [ResultsStr; {['Run',num2str(ResultNum),' ',num2str(Kf),' ',num2str(Ki)]}];
end
set(handles.ResultsList,'String',ResultsStr);
% Store the new ResultsData
handles.ResultsData = ResultsData;
guidata(h,handles)
%---------------------------------------------------------
% Callback for the Remove push button
%---------------------------------------------------------
function varargout = RemoveButton_Callback(h, eventdata, handles)
% hObject handle to RemoveButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Callback of the uicontrol handles.RemoveButton.
currentVal = get(handles.ResultsList,'Value');
resultsStr = get(handles.ResultsList,'String');
numResults = size(resultsStr,1);
% Remove the data and list entry for the selected value
resultsStr(currentVal) =[];
handles.ResultsData(currentVal)=[];
% If there are no other entries, disable the Remove and Plot button
% and change the list sting to <empty>
if isequal(numResults,length(currentVal)),
resultsStr = {'<empty>'};
currentVal = 1;
set([handles.RemoveButton,handles.PlotButton],'Enable','off')
end
% Ensure that list box Value is valid, then reset Value and String
currentVal = min(currentVal,size(resultsStr,1));
set(handles.ResultsList,'Value',currentVal,'String',resultsStr)
% Store the new ResultsData
guidata(h,handles)
謝謝math大哥,你說的我能理解,可是我對於藍色代碼段起始部分仍是不能理解,可否具體解釋這幾句的含義?
if isfield(handles,'ResultsData') & ~isempty(handles.ResultsData)
ResultsData = handles.ResultsData;不能理解這裏面的幾個ResultsData!
% Determine the maximum run number currently used.
maxNum = ResultsData(length(ResultsData)).RunNumber;這怎麼理解?
ResultNum = maxNum+1;
else, % Set up the results data structure
ResultsData = struct('RunName',[],'RunNumber',[],...
'KiValue',[],'KfValue',[],'timeVector',[],'outputVector',[]);此句是否在爲結構體ResultsData增長成員變量?
ResultNum = 1;
end
if isequal(ResultNum,1),
%--Enable the Plot and Remove buttons
set([handles.RemoveButton,handles.PlotButton],'Enable','on')
end
該實例演示功能說明:
這個例子包括的gui典型功能以下:
edit和slider的聯合使用;
用GUI設置simulink模塊的參數;
用GUI按鈕運行simulink模塊;
在GUI的listbox中顯示simulink運行結果;
點選listbox,點擊按鈕plot繪製運行結果的圖形;
用一個help按鈕打開一個help連接;
若是有用到這些功能的朋友能夠在matlab help 文件中搜索gui,在GUI Application的例子中查看相應的fig文件和m文件,也能夠在這個目錄下學習其它的實例!
爲便於交流和探討,附上主要代碼和GUI界面!
% --- Outputs from this function are returned to the command line.
function varargout = f14ex_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
%--------------------------------------------------------
% Ensure that the Simulink model is open
%---------------------------------------------------------
function model_open(handles)
% Make sure the diagram is still open
if isempty(find_system('Name','f14')),
open_system('f14'); open_system('f14/Controller')
set_param('f14/Controller/Gain','Position',[275 14 340 56])
figure(handles.F14ControllerEditor)
% Put values of Kf and Ki from the GUI into the Block dialogs
set_param('f14/Controller/Gain','Gain',...
get(handles.KfCurrentValue,'String'))%爲何simulink中該Gain模塊沒有命名
set_param('f14/Controller/Proportional plus integral compensator',...
'Numerator',...
get(handles.KiCurrentValue,'String'))
end
%--------------------------------------------------------
% Callback for Proportional(Kf) slider
%---------------------------------------------------------
function varargout = KfValueSlider_Callback(h, eventdata, handles)
% hObject handle to KfValueSlider (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
%get(hObject,'Min') and get(hObject,'Max') to determine range of slider
% Ensure model is open
model_open(handles)
% Get the new value for the Kf Gain from the slider
NewVal = get(h,'Value');
% Set the value of the KfCurrentValue to the new value set by slider
set(handles.KfCurrentValue,'String',NewVal)
% Set the Gain parameter of the Kf Gain Block to the new value
set_param('f14/Controller/Gain','Gain',num2str(NewVal))
%--------------------------------------------------------
% Callback for Kf Current value text box
%---------------------------------------------------------
function varargout = KfCurrentValue_Callback(h, eventdata, handles)
% hObject handle to KfCurrentValue (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit1 as text
% str2double(get(hObject,'String')) returns contents of edit1 as a double
% Ensure model is open
model_open(handles)
% Get the new value for the Kf Gain
NewStrVal = get(h,'String');
NewVal = str2double(NewStrVal);
% Check that the entered value falls within the allowable range
if isempty(NewVal) | (NewVal< -5) | (NewVal>0),
% Revert to last value, as indicated by KfValueSlider
OldVal = get(handles.KfValueSlider,'Value');
set(h,'String',OldVal)
else
% Set the value of the KfValueSlider to the new value
set(handles.KfValueSlider,'Value',NewVal)
% Set the Gain parameter of the Kf Gain Block to the new value
set_param('f14/Controller/Gain','Gain',NewStrVal)
end
% ------------------------------------------------------------
% Callback for Integral(Ki) slider
% ------------------------------------------------------------
function varargout = KiValueSlider_Callback(h, eventdata, handles)
% hObject handle to KiValueSlider (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
% Ensure model is open
model_open(handles)
% Get the new value for the Ki Gain from the slider
NewVal = get(h,'Value');
% Set the value of the KiCurrentValue to the new value set by slider
set(handles.KiCurrentValue,'String',NewVal)
% Set the Numerator parameter of the Ki Tranfer function Block to the new value
set_param('f14/Controller/Proportional plus integral compensator','Numerator',num2str(NewVal))
% ------------------------------------------------------------
% Callback for Ki Current value text box
% ------------------------------------------------------------
function varargout = KiCurrentValue_Callback(h, eventdata, handles)
% hObject handle to KiCurrentValue (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit1 as text
% str2double(get(hObject,'String')) returns contents of edit1 as a double
% Ensure model is open
model_open(handles)
% Get the new value for the Ki Gain
NewStrVal = get(h,'String');
NewVal = str2num(NewStrVal);
% Check that the entered value falls within the allowable range
if isempty(NewVal) | (NewVal< -5) | (NewVal>0),
% Revert to last value, as indicated by KiValueSlider
OldVal = get(handles.KiValueSlider,'Value');
set(h,'String',OldVal)
else% Use new Ki value
% Set the value of the KiValueSlider to the new value
set(handles.KiValueSlider,'Value',NewVal)
% Set the Numerator parameter of the Ki Tranfer function Block to the new value
set_param('f14/Controller/Proportional plus integral compensator','Numerator',NewStrVal)
end
% ------------------------------------------------------------
% Callback for the Simulate and store results button
% ------------------------------------------------------------
function varargout = SimulateButton_Callback(h, eventdata, handles)
% hObject handle to SimulateButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[timeVector,stateVector,outputVector] = sim('f14');
% Retrieve old results data structure
if isfield(handles,'ResultsData') & ~isempty(handles.ResultsData)
ResultsData = handles.ResultsData;
% Determine the maximum run number currently used.
maxNum = ResultsData(length(ResultsData)).RunNumber;
ResultNum = maxNum+1;
else, % Set up the results data structure
ResultsData = struct('RunName',[],'RunNumber',[],...
'KiValue',[],'KfValue',[],'timeVector',[],'outputVector',[]);
ResultNum = 1;
end
if isequal(ResultNum,1),
%--Enable the Plot and Remove buttons
set([handles.RemoveButton,handles.PlotButton],'Enable','on')
end
% Get Ki and Kf values to store with the data and put in the results list.
Ki = get(handles.KiValueSlider,'Value');
Kf = get(handles.KfValueSlider,'Value');
ResultsData(ResultNum).RunName = ['Run',num2str(ResultNum)];
ResultsData(ResultNum).RunNumber = ResultNum;
ResultsData(ResultNum).KiValue = Ki;
ResultsData(ResultNum).KfValue = Kf;
ResultsData(ResultNum).timeVector = timeVector;
ResultsData(ResultNum).outputVector = outputVector;
% Build the new results list string for the listbox
ResultsStr = get(handles.ResultsList,'String');
if isequal(ResultNum,1)
ResultsStr = {['Run1 ',num2str(Kf),' ',num2str(Ki)]};
else
ResultsStr = [ResultsStr; {['Run',num2str(ResultNum),' ',num2str(Kf),' ',num2str(Ki)]}];
end
set(handles.ResultsList,'String',ResultsStr);
% Store the new ResultsData
handles.ResultsData = ResultsData;
guidata(h,handles)
代碼運行時間的計時方法:
一、整段程序代碼的計時:
tic 。。。。
toc 表示計算tic和tc之間的時間
這種方法只能計算出大致的時間
二、etime(t1,t2)來計算t1,t2之間的時間差,應用的形式:
t0=clock
程序段
etime(clock,t0)
三、也能夠用cputime變量來完成的
應用方法:
t0=cputime
程序段
t1=cputime-t0
給出三種方法更明確的幫助文件吧。
Clock 以一個時間向量給出當前時間
c = [year month day hour minute seconds]
cputime cpu運行時間
Examples
The following code returns the CPU time used to run surf(peaks(40)).
t = cputime; surf(peaks(40)); e = cputime-t
e = 0.4667
tic與toc
tic starts a stopwatch timer. %單詞解釋秒錶計時器。
toc prints the elapsed time since tic was used.
t = toc returns the elapsed time in t.
etime
e = etime(t2,t1) returns the time in seconds between vectors t1 and t2. The two vectors must be six elements long, in the format returned by clock: T = [Year Month Day Hour Minute Second]
具體狀況以下:
我採集了一幅圖像有兩個光斑,在個人GUI界面上有一個axes (handles.axes1),現想把其中的一個光斑在axes1中畫一個小的axes專門用來這個光斑,也就是選取其中一個光斑顯示的同時,原來採集的圖像也不被覆蓋,就在指定的座標軸中顯示,懇請你們指點!
參考一下:
clear,clc,close all;
x=0:0.01:2*pi;
y1=x.^2;
y2=sin(x);
plot(x,y1);
xlabel('x');ylabel('x^2');
%---------------------------
axes('position',[0.23,0.5,0.35,0.35]);
plot(x,y2);
xlabel('x');ylabel('sin(x)');
k = waitforbuttonpress;
point1 = get(gca,'CurrentPoint'); % button down detected
finalRect = rbbox; %鼠標拖動時在矩形框四周造成橡皮線條
point2 = get(gca,'CurrentPoint'); % button up detected
point1 = point1(1,1:2); % extract x and y
point2 = point2(1,1:2);
p1 = min(point1,point2); % calculate locations
offset = abs(point1-point2); % and dimensions
x = [p1(1) p1(1)+offset(1) p1(1)+offset(1) p1(1) p1(1)];
y = [p1(2) p1(2) p1(2)+offset(2) p1(2)+offset(2) p1(2)];
hold on
axis manual
plot(x,y)
各位大蝦,我接觸Matlab GUI時間不長,就一個星期左右,我目的是想作一個簡單的界面
跟這附件的同樣就好了,不過我輸入代碼CALLBACK的時候有點問題,但願你們指導一下:
文件:
打開——uigetfile
保存——uiputfile
打印設置——dlg=pagesetupdlg
打印預覽——printpreview
打印——printdlg
退出——exit
編輯:
導入圖片——j=i;imshow(j)
導出圖片——imwrite(j,'new.tif')
選取區域——b=imcrop(j);imshow(b);j=b
清除——clear;i=0;imshow(i)
復原——imshow(i);j=i
圖像處理:
灰度加強——b=imadjust(j,[0.3 0.7],[]);imshow(b);j=b
對比加強——b=imadjust(j,stretchlim(j));imshow(b);j=b
邊緣加強——h=fspecial('prewitt');b=imfilter(j,h);imshow(b);j=b
表面銳化——h=fspecial('sobel');b=filter2(h,j);imshow(b);j=b
平滑處理——b=filter2(fspecial('average',7),j)/255;imshow(b);j=b
二值化——b=im2bw(j,0.25);imshow(b);j=b
中值過濾——b=medfilt2(j,[3 3]);imshow(b);j=b
高斯過濾——b=ordfilt2(j,9,ones(3,3));imshow(b);j=b
圖像分析:
邊緣檢測(log)——b=edge(j,'log');imshow(b);j=b
邊緣檢測(canny)——b=edge(j,'canny');imshow(b);j=b
邊緣檢測(sobel)——b=edge(j,'sobel');imshow(b);j=b
反色——b=~j;imshow(b);j=b
面積測量——b=imcomplement(j);area=bwarea(b);area
我就是對每個按鈕Callback而後輸入上面的代碼,結果好多都有問題,不知道究竟問題出在哪呢?
ilovematlab.JPG (130.09 KB)
2008-3-21 04:21 PM
文件:
打開——uigetfile
保存——uiputfile
打印設置——dlg=pagesetupdlg
打印預覽——printpreview
打印——printdlg
退出——exit
編輯:
導入圖片——j=i;imshow(j)
導出圖片——imwrite(j,'new.tif')
選取區域——b=imcrop(j);imshow(b);j=b
清除——clear;i=0;imshow(i)
復原——imshow(i);j=i
圖像處理:
灰度加強——b=imadjust(j,[0.3 0.7],[]);imshow(b);j=b
對比加強——b=imadjust(j,stretchlim(j));imshow(b);j=b
邊緣加強——h=fspecial('prewitt');b=imfilter(j,h);imshow(b);j=b
表面銳化——h=fspecial('sobel');b=filter2(h,j);imshow(b);j=b
平滑處理——b=filter2(fspecial('average',7),j)/255;imshow(b);j=b
二值化——b=im2bw(j,0.25);imshow(b);j=b
中值過濾——b=medfilt2(j,[3 3]);imshow(b);j=b
高斯過濾——b=ordfilt2(j,9,ones(3,3));imshow(b);j=b
圖像分析:
邊緣檢測(log)——b=edge(j,'log');imshow(b);j=b
邊緣檢測(canny)——b=edge(j,'canny');imshow(b);j=b
邊緣檢測(sobel)——b=edge(j,'sobel');imshow(b);j=b
反色——b=~j;imshow(b);j=b
面積測量——b=imcomplement(j);area=bwarea(b);area
clear;
close all;
x=0:0.01:2*pi;
y=sin(x);
z=cos(x);
figure;
subplot(2,1,1);
hsin=plot(x,y);
saveas(hsin, 'output1.jpg')
axis([0 2*pi -1 1]);
subplot(2,1,2);
hcos=plot(x,z);
axis([0 2*pi -1 1]);
在GUI中按了某個按鈕以後,想用IE打開網頁,因爲頁面中有javascript腳本,因此用MATLAB自帶的瀏覽器不能運行那位朋友知道怎樣打開IE並添加想要的地址 或者改變Matlab自帶的瀏覽器爲IE。
解決辦法:
web -browser www.ilovematlab.cn
web
web url
web url -new
web url -notoolbar
web url -noaddressbox
web url -helpbrowser
web url -browser
web(...)
stat = web('url', '-browser')
[stat, h1] = web
[stat, h1, url] = web
由於剛剛接觸matlab gui,實在不懂,但願指教。硬件我已經有了,帶pwm輸出端的芯片,直流電機,和等一些配件。個人願望是,經過matlab gui窗口輸入必定範圍內不一樣的數值(表示不一樣的電壓),經過rs232的通信,傳遞給個人芯片,其實就是用不一樣的pwm電壓,來控制直流電機的轉速。
你這個問題有2部分:
1: GUI 設計, 參照視頻教學
2: 串口數據讀寫(你主要是寫)
這裏serial port問題, 參照:本板塊裏,其餘串口數據讀寫的程序,這裏有好幾個!
若是你想試一下簡單的,假設你的rs232在com1上:
s = serial('COM1');
fopen(s)
fprintf(s,'*IDN?')
idn = fscanf(s);
fclose(s)
我想點一下按鈕存一個數在excel表裏。好比第一個存在A2,那麼下一個存在A3。是這樣的一個問題:
axes中讀入一圖片 而後 點擊圖片上任一點就能夠獲得這點的座標值 同時顯示在listbox中,而後點擊store按鈕存儲在excel表中,一共有800張圖因此有800個值,其餘我都能實現了就是存儲這部分不知道要怎麼弄了。
程序是這樣的:
boxX是顯示x座標的listbox
function currentpoint_Callback(hObject, eventdata, handles)
% hObject handle to currentpoint (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global A;
global i;
axes(handles.axes1); %用axes命令設定當前操做的座標軸爲axes1;
set(gcf,'WindowButtonDownFcn',@ButttonDownFcn);
% 回調函數
function ButttonDownFcn(src,event)
pt = get(gca,'CurrentPoint');
x = pt(1,1);
y = pt(1,2);
%str=fprintf('x=%.3f,y=%.3f\n',x,y);
set(findobj('tag','boxX'),'String',num2str(x));
set(findobj('tag','boxY'),'string',num2str(y));
% --- Executes on button press in store.
function store_Callback(hObject, eventdata, handles)
% hObject handle to store (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
global A;
global i;
listX=get(findobj('tag','boxX'),'string');
listx=str2num(listX);
i=size(listx,1);
if listx==0
return
else
i=i+1;
s=sprintf('A%d',i);
xlswrite('e:\matlab\xyZ.xls',listx,'sheet1',s);
end
解決辦法:
問題出在下面這段代碼裏:
global A;
global i;
listX=get(findobj('tag','boxX'),'string');
listx=str2num(listX);
i=size(listx,1);
if listx==0
return
else
i=i+1;
s=sprintf('A%d',i);
xlswrite('e:\matlab\xyZ.xls',listx,'sheet1',s);
end
你把i聲明爲全局變量是對的,但每次你都經過i=size(listx,1);語句改變了它的值,因此每次它的初始值都是1,再用i=i+1它的值就是2,
s=sprintf('A%d',i);每次獲得的都是A2,這樣每次都是向A2裏面寫數據了。
修改辦法:
在程序初始的地方,如OpeningFcn中聲明i,並初始化:
global i
i=0;
把下面語句中的 i=size(listx,1);去掉。
global A;
global i;
listX=get(findobj('tag','boxX'),'string');
listx=str2num(listX);
% i=size(listx,1);
if listx==0
return
else
i=i+1;
s=sprintf('A%d',i);
xlswrite('e:\matlab\xyZ.xls',listx,'sheet1',s);
end
另,儘可能少用i、j等做爲變量。建議換成別的名稱,如number_of_point等。
調試下面的例子:
%% LaTeX Examples--Some well known equations rendered in LaTeX
%
figure('color','white','units','inches','position',[2 2 4 6.5]);
axis off
%% A matrix; LaTeX code is
% \hbox {magic(3) is } \left( {\matrix{ 8 & 1 & 6 \cr
% 3 & 5 & 7 \cr 4 & 9 & 2 } } \right)
h(1) = text('units','inch', 'position',[.2 5], ...
'fontsize',14, 'interpreter','latex', 'string',...
['$$\hbox {magic(3) is } \left( {\matrix{ 8 & 1 & 6 \cr'...
'3 & 5 & 7 \cr 4 & 9 & 2 } } \right)$$']);
%% A 2-D rotation transform; LaTeX code is
% \left[ {\matrix{\cos(\phi) & -\sin(\phi) \cr
% \sin(\phi) & \cos(\phi) \cr}}
% \right] \left[ \matrix{x \cr y} \right]
%
% $$ \left[ {\matrix{\cos(\phi)
% & -\sin(\phi) \cr \sin(\phi) & \cos(\phi) % \cr}}
% \right] \left[ \matrix{x \cr y} \right] $$
%
h(2) = text('units','inch', 'position',[.2 4], ...
'fontsize',14, 'interpreter','latex', 'string',...
['$$\left[ {\matrix{\cos(\phi) & -\sin(\phi) \cr'...
'\sin(\phi) & \cos(\phi) \cr}} \right]'...
'\left[ \matrix{x \cr y} \right]$$']);
%% The Laplace transform; LaTeX code is
% L\{f(t)\} \equiv F(s) = \int_0^\infty\!\!{e^{-st}f(t)dt}
% $$ L\{f(t)\} \equiv F(s) = \int_0^\infty\!\!{e^{-st}f(t)dt} $$
% The Initial Value Theorem for the Laplace transform:
% \lim_{s \rightarrow \infty} sF(s) = \lim_{t \rightarrow 0} f(t)
% $$ \lim_{s \rightarrow \infty} sF(s) = \lim_{t \rightarrow 0}
% f(t) $$
%
h(3) = text('units','inch', 'position',[.2 3], ...
'fontsize',14, 'interpreter','latex', 'string',...
['$$L\{f(t)\} \equiv F(s) = \int_0^\infty\!\!{e^{-st}'...
'f(t)dt}$$']);
%% The definition of e; LaTeX code is
% e = \sum_{k=0}^\infty {1 \over {k!} }
% $$ e = \sum_{k=0}^\infty {1 \over {k!} } $$
%
h(4) = text('units','inch', 'position',[.2 2], ...
'fontsize',14, 'interpreter','latex', 'string',...
'$$e = \sum_{k=0}^\infty {1 \over {k!} } $$');
%% Differential equation
% The equation for motion of a falling body with air resistance
% LaTeX code is
% m \ddot y = -m g + C_D \cdot {1 \over 2} \rho {\dot y}^2 \cdot A
% $$ m \ddot y = -m g + C_D \cdot {1 \over 2} \rho {\dot y}^2
% \cdot A $$
%
h(5) = text('units','inch', 'position',[.2 1], ...
'fontsize',14, 'interpreter','latex', 'string',...
['$$m \ddot y = -m g + C_D \cdot {1 \over 2}'...
'\rho {\dot y}^2 \cdot A$$']);
%% Integral Equation; LaTeX code is
% \int_{0}^{\infty} x^2 e^{-x^2} dx = \frac{\sqrt{\pi}}{4}
% $$ \int_{0}^{\infty} x^2 e^{-x^2} dx = \frac{\sqrt{\pi}}{4} $$
%
h(6) = text('units','inch', 'position',[.2 0], ...
'fontsize',14, 'interpreter','latex', 'string',...
'$$\int_{0}^{\infty} x^2 e^{-x^2} dx = \frac{\sqrt{\pi}}{4}$$');
更多內容見:http://www.latex-project.org/.
修改第431行的代碼以下:
htmp = uicontrol(tabs(i), ...
'Style', 'text', ...
'foregroundcolor',[1,0,0],...%
改變字體顏色爲紅色
'fontsize',20,...%
改變字體大小爲
20
'Enable', 'inactive', ...
'String', strings{i}, ...
'HorizontalAlign', 'center', ...
'Units', 'pixels', ...
'Position', ppos, ...
'ButtonDownFcn', butDownFcn ...
);
set(htmp,'Units', 'normalized');
就能夠修改標籤頁的字體顏色和大小了。
我把RGB圖像分色,分紅紅色R,綠色G,和藍色B!請問怎樣把他們合成彩色圖。爲何下面這個很差用??
[imX, mapX] = rgb2ind(redIm, greenIm, blueIm, 256);
解決辦法:
r=imread('C:\r.gif');
g=imread('C:\g.gif');
b=imread('C:\b.gif');
G(:,:,1)=r;
G(:,:,2)=g;
G(:,:,3)=b;
axes(handles.axes2);
imshow(G);
有兩條曲線,分別爲數據1{x1,y1},數據2{x2,y2},x,y分別是n個數值
使用
plot(x1,y1);
hold on;
plot(x2,y2);
命令同時在一個圖裏繪製出兩條曲線,但是若是要刪除其中一條繪製好的曲線,只保留另外一條曲線,應該怎麼作。
最佳答案:
利用set(h,'visible','off');語句就能夠實現你要的功能。例如:
x1=0:pi/50:2*pi;
y1=sin(x1);
x2=0:pi/50:2*pi;
y2=cos(x2);
axes(handles.axes2);
h1=plot(x1,y1);
hold on;
h2=plot(x2,y2);
handles.h1=h1;
handles.h2=h2;
guidata(hObject,handles);
若是你想刪除plot(x2,y2)繪的圖,能夠在你的代碼中加入:
h2=handles.h2;
set(h2,'visible','off');
這時,第二條曲線就刪除了。
這幾天在論壇裏又收穫很多,總結了一些關於獲得隨機矩陣的函數,但願對你們有所幫助。
歡迎回帖給與補充,呵呵,謝謝先。
1、randperm
randperm(n);
產生從零到n長度爲n的隨機整數
例如
>> randperm(10)
ans =
8 2 10 7 4 3 6 9 5 1
>>
2、randsrc
無參數形式,隨機輸出-1或1;
randsrc(m,n);
randsrc(m);
輸出m*n階或m*m階矩陣,元素爲隨機出現的-1或1,機率爲1/2;
randsrc(m,n,alphabet);
輸出m*n階矩陣,元素由alphabet肯定,機率等同;
randsrc(m,n,[alphabet;prob]);
prob參數肯定每元素的出現機率。
例如
>> randsrc
ans =
1
>> randsrc(5)
ans =
1 -1 -1 -1 1
-1 1 -1 -1 -1
-1 -1 -1 -1 -1
1 -1 -1 1 1
1 1 1 -1 1
>> randsrc(2,2,[1 2 3 4])
ans =
1 4
3 1
3、randint
無參數形式隨機輸出0或1;
randint(m,n);
randint(m);
按一樣機率輸出由0或1組成的m*m階或m*n階矩陣
randint(m,n,rg);
按照一樣機率隨機輸出[0,rg-1](rg>0)或[rg+1,0](rg<0)或[minrg,maxrg](rg爲數組)之間的數字。
例如
>> randint(2,3)
ans =
1 1 0
1 0 0
>> randint(2,3,8)
ans =
1 2 1
5 4 5
>> randint(1,2,[2 4])
ans =
3 4
4、unifrnd
unifrnd(a,b);
unifrnd(a,b,m);
unifrnd(a,b,m,n);
ab爲一樣長度的向量或矩陣,產生與ab一樣大小的向量或矩陣,對應元素爲位於ab對應元素之間的隨機數,若是有m或m,n參數,則產生m*m或m*n階矩陣。
例如
>> unifrnd(3,4)
ans =
3.0648
>> unifrnd(2,4,4)
ans =
3.9767 2.6679 3.5207 2.7596
3.1656 2.8658 3.0596 3.5667
2.8470 2.4519 3.2811 3.3617
3.0310 3.1596 2.4181 2.9222
5、unidrnd
unidrnd(N);
unidrnd(N,m,n);
unidrnd(N,m);
產生不大於N的隨機整數,N要求爲整數矩陣,若是沒有mn參數,則產生與N相同大小,不然產生m*n或m*m階矩陣。
例如
>> unidrnd(2,4)
ans =
1 1 2 1
2 2 1 1
2 2 1 1
1 1 1 2
>> unidrnd([1 2 5 6 7 2 3 4 ])
ans =
1 1 4 4 1 1 1 3
不當之處,望你們不吝指教。
1.如何將音樂文件做爲matlab GUI的背景音樂來播放?
matlab支持每一個採樣位爲8或16的wav音樂。咱們假設原始文件爲某個mp3文件。咱們所要作的就是,下載一個MP3轉WAV的軟件,最多見的就是千千靜聽了。千千靜聽的右鍵菜單內有一個選項爲【轉換格式...】,咱們將其轉換爲採樣位爲16的WAV文件。
若是音樂文件比較大,建議將採樣率更改成小一點的。。。
咱們要作的第一步,就是將該文件的數據轉化爲matlab能夠識別的矩陣,這用到一個函數:waveread。設該wav文件名爲a.wav,則句型爲:
[y,Fs,bits] = wavread('a.wav'); %將a.wav 放到當前目錄
其中:
y——音樂數據;
Fs——採樣率;
bits——採樣位,默認值爲16。
2.如何播放與中止音樂?
這個步驟,可能不少人會想到如下方法:
sound(y,Fs,bits)
其實,這種方法有個問題:一旦播放了,就無法中止。那麼,有沒有辦法能夠隨意播放和中止音樂呢?
答案是:有。
讓聲卡發出聲音,實際是一個模擬信號輸出到硬件(聲卡)的過程。matlab有一個模擬輸出函數庫,能夠創建模擬輸出對象和通道:analogoutput函數。
方法以下:
[y,Fs,bits] = wavread('dl.wav'); %獲取音樂數據
ao = analogoutput('winsound'); %創建硬件對象
addchannel(ao,[1 2]); %建立聲音輸出通道
set(ao,'SampleRate',Fs) %設置採樣率
data1 =y(:,1); %雙聲道
data2 =y(:,2);
putdata(ao,[data1 data2]); %往聲卡堆音樂數據
start(ao); %輸出音樂數據
此時還能夠繼續堆數,一旦堆得數輸出完,ao自動中止。
當想讓音樂中止時,只須要:stop(ao)便可。
3.暫停/繼續
暫停/繼續的功能,不能按上述方法實現。
能夠先堆1秒的數據,而後TimerFcn設爲1秒,每次進入TimerFcn時只堆1秒的數據,若是暫停標誌爲true,則堆1秒的數據0;若暫停標誌爲false,則堆1秒的音樂數據。
如此,暫停功能便可實現,並且,載入的音樂數據理論能夠無限大。。。
4.循環播放的另外一種方法
除了【俄羅斯方塊】程序中的方法外,還能夠用下面更簡單的方法,來實現循環播放。
模擬輸出對象的屬性以下:
BufferingConfig = [1024 1173]
BufferingMode = Auto
Channel = [2x1 aochannel]
ClockSource = Internal
EventLog = [1x2 struct]
InitialTriggerTime = [2009 9 12 10 25 11.156]
MaxSamplesQueued = 1.34154e+008
Name = winsound0-AO
RepeatOutput = 0
Running = On
RuntimeErrorFcn = @daqcallback
SampleRate = 11025
SamplesAvailable = 991382
SamplesOutput = 207083
SamplesOutputFcn = []
SamplesOutputFcnCount = 1024
Sending = On
StartFcn = []
StopFcn = []
Tag =
Timeout = 1
TimerFcn = global ao xianjian;putdata(ao,[xianjian(:,1) xianjian(:,2)]);
TimerPeriod = 100
TriggerFcn = []
TriggersExecuted = 1
TriggerType = Immediate
Type = Analog Output
UserData = []
WINSOUND specific properties:
BitsPerSample = 16
StandardSampleRates = On
在TimerFcn中設置RepeatOutput屬性,能夠實現循環播放。
如題,想在AXES軸上畫曲線,AXES軸背景顏色用黑色,GRID顏色默認也是黑色,若是設爲ON,看不見GRID網格線,想改變GRID網格線的顏色,發現沒有相關的屬性,請高人指點。
解決方法:
axes軸裏面的屬性:xcolor、ycolor、zcolor,設定這個屬性值,能夠改變座標軸和grid的顏色。
h=axes(...);%建立axes軸,獲得其句柄
set(h,'xcolor',[0,1,1],'ycolor',[1,0,0],'xgrid','on','ygrid','on');
例子:
function annotation_property_line
dat = rand(50,1);
hLine = plot(dat);
plotMean % Nested function draws a line at mean value
set(get(get(hLine,'Annotation'),'LegendInformation'),...
'IconDisplayStyle','off'); % Exclude line from legendlegend('mean')
function plotMean
xlimits = get(gca,'XLim');
meanValue = mean(dat);
meanLine = line([xlimits(1) xlimits(2)],...
[meanValue meanValue],'Color','k','LineStyle','-.');
end
end
紅色部分,'IconDisplayStyle'爲'on'時,表示在legend中,爲‘off’時,表示排除在外。
clear all
xita=0;
fin=0;
xita_array=[-40:2:40]/180*pi;
fin_array=[-40:2:40]/180*pi;
cnt1=length(xita_array);
cnt2=length(fin_array);
result_matrix=zeros(cnt1,cnt2);
%
行是
xita,
列是
fin
ceshi = [];
for c1=1:cnt1
xita=xita_array(c1);
for c2=1:cnt2
fin=fin_array(c2);
R=[cos(fin)^2*cos(xita)+sin(fin)^2,sin(fin)*cos(fin)*(cos(xita)-1),cos(fin)*sin(xita);sin(fin)*cos(fin)*(cos(xita)-1),sin(fin)^2*cos(xita)+cos(fin)^2,sin(fin)*sin(xita);-cos(fin)*sin(xita),sin(fin)*sin(xita),cos(xita)];
A=zeros(3,3);
A(1,1)=1;
A(1,2)=-R(2,1);
A(1,3)=R(1,1);
A(2,1)=1;
A(2,2)=(R(2,1)-sqrt(3)*R(2,2))/2;
A(2,3)=(sqrt(3)*R(1,2)-R(1,1))/2;
A(3,1)=1;
A(3,2)=(R(2,1)+sqrt(3)*R(2,2))/2;
A(3,3)=(-sqrt(3)*R(1,2)-R(1,1))/2;
delta=det(A);
ceshi = [ceshi delta];
%向其中連續追加數據,獲得1xn的矩陣
% ceshi = [ceshi
;
delta];%
獲得
nx1
的矩陣
end
end
%
加入三維曲面繪製程序
[X,Y]=meshgrid(xita_array,fin_array);
v1 = reshape(ceshi, 41, 41);
meshz(X,Y,v1); view(3);
clear
m=30;
z=1.2*(0:m)/m;
r=ones(size(z));
theta=(0:m)*2*pi/m;
x1=r'*cos(theta);y1=r'*sin(theta);
z1=z'*ones(1,m+1);
x=(-m:2:m)/m;
x2=x'*ones(1,m+1);y2=r'*cos(theta);
z2=r'*sin(theta);
surf(x1,y1,z1);
axis equal,axis off
hold on
surf(x2,y2,z2);
axis equal ,axis off
title('
兩個等直徑圓管的交線
');
hold off
u0=csvread('data.csv')很差用,由於個人文件第一行是文本,好像csvread要求所讀取的csv文件必須都是數據。什麼語句能刪除csv文件裏面的第一行,而後讀取單元格A3到A10的數據?(假設csv裏面有20*20的數據)
方法:
用以下方式讀取:
csvread('D:\chengji.txt',1,0); %把第一行的內容排除
liu1,liu2,liu3
80,75,65
60,65,35
>> csvread('D:\chengji.txt',1,0)
ans =
80 75 65
60 65 35
我在雙對數座標系(loglog)中有一組座標點[x0 y0],請問如何在些點之間作直線插值,讓插值獲得的點落在座標之間的直線上。
因爲對數座標系的緣由,我用 yi = interp1(x0, y0, xi) 獲得的點 (xi yi) 都不在直線上,以下圖所示,應如何讓這些插值點落在直線上?
figure;
x0=[0.1;0.2;0.4;0.7;1];
y0=[100;10;3;1.5;1.2];
i=(0.1:0.01:1);
x1=log10(x0);
y1=log10(y0);
xi=log10(i);
yi=interp1(x1,y1,xi);
x2=10.^xi;
y2=10.^yi;
loglog(x0,y0);
hold on;
plot(x2,y2,'.r');
代碼:
rgbImage = imread('peppers.png');
figure(1);
subplot(1,2,1);
imshow(rgbImage);
[rows cols numberOfColors] = size(rgbImage);
X2= cols/2;
rgbImage(:,1:X2, 1) = 255;
rgbImage(:,1:X2, 2) = 255;
rgbImage(:,1:X2, 3) = 255;
redBand = rgbImage(:,:,1);%圖像的紅色帶部分
greenBand = rgbImage(:,:,2);%圖像的綠色帶部分
blueBand = rgbImage(:,:,3);%圖像的藍色帶部分
coveredImage = cat(3, redBand, greenBand, blueBand); %合成圖像
subplot(1,2,2);
imshow(coveredImage);
set(gcf, 'Position', get(0, 'ScreenSize')); % Maximize figure.
運行結果:
function listbox_callback(hObject,eventdata,handles)
get(handles.figure1,'SelectionType');
index_selected = get(handles.listbox,'Value');
file_list = get(handles.listbox,'String');
if strcmp(get(handles.figure1,'SelectionType'),'open') % 設置figure的屬性‘selectiontype’爲‘open’表明雙擊
[data,fs,bits] = wavread(file_list{index_selected});
end
7九、如何刪除矩陣中的NaN
好比: aaa=[1 3 5; 2 NaN 6; 7 8 9; NaN NaN 7];
我想最終獲得: bbb=[1 3 5; 7 8 9];
a=[1 3 5; 2 NaN 6; 7 8 9; NaN NaN 7];
[m,n]=find(isnan(a)==1);
a(m,:)=[]
clear,clc,close all;
t=-3:0.1:3;
[x,y]=meshgrid(t,t);
z=x.^2-y.^2;
[x1,z1]=meshgrid(t,-10:0.4:10);
while 1
for m=-3:0.5:3;
y1=m+0*x1;
clf
h=mesh(x1,y1,z1);
hold on;
surf(x,y,z);
xlabel('x');ylabel('y');zlabel('z');
set(gcf,'units','normalized','position',[0,0,1,1]);
pause(1);
end;
end
function myname()
global m c k
m=1;
k=6;
c=2.5;
[T,Y]=ode45(@eqn1,[0,1],[0;0]);
plot(T,Y);
function xdot=eqn1(t,x)
xdot=[x(2);-6*x(1)-2.5*x(2)+1*(2*sin(t))];
end
end
有一個文件夾,裏面有一些圖片(好比'ab.bmp', '24r.bmp', 'f5tr.bmp'三幅),圖片名沒有規律,如何逐一將圖片名讀入變量pic中?
代碼:
picstr=dir('*.bmp');
[r,c]=size(picstr);
pic=cell(r,1);
for i=1:r
pic=imread(picstr(i).name);
end
clear,clc,close all;
x=0:0.01:10;
y=exp(-x)-cos(x);
plot(x,y)
x=1;
while 1
df=sin(x)-exp(-x);
f=exp(-x)-cos(x);
if(abs(f/df)<1e-6)
break;
end
x=x-f/df;
end
format long
x
hold on;
plot(x,0,'m.','MarkerSize',25);
text(x+0.2,0,'\leftarrow
方程根
');
我在M文件裏寫了一個while循環,運行GUI之後,在GUI範圍內,鼠標任意點擊某處,循環運行一次獲得結果,即經過鼠標點擊,手動控制一次一次循環知道結束。
一、定義全局變量:global begin; 用來控制循環。定義 global num; 來控制循環次數,初始值爲num=1
二、在windowbuttondownFcn函數中加入while循環。
三、windowbuttonupFcn中改變begin的值。
這樣,沒點鼠標一次,就執行一次while循環。
function figure1_WindowButtonDownFcn(hObject, eventdata, handles)
global begin num
begin=1;
while 1
if begin==1
disp('
循環開始
');
num=num+1;
end
if num==20%
設定循環
20
次
return
end
pause(1);
end
function figure1_WindowButtonUpFcn(hObject, eventdata, handles)
global begin;
begin=0;
% The current extension mode is zero-padding (see dwtmode).
% Load original image.
load woman; %woman if a mat file, not a picture.
% X contains the loaded image.
% map contains the loaded colormap.
nbcol = size(map,1);
% if the picture is type of truecolor, map does not exist.
%info = imfinfo('image');查看一下圖像屬性,若是是truecolor的都沒有colormap
% Perform single-level decomposition
% of X using db1.
[cA1,cH1,cV1,cD1] = dwt2(X,'db1');
% Images coding.
cod_X = wcodemat(X,nbcol);
cod_cA1 = wcodemat(cA1,nbcol);
cod_cH1 = wcodemat(cH1,nbcol);
cod_cV1 = wcodemat(cV1,nbcol);
cod_cD1 = wcodemat(cD1,nbcol);
dec2d = [...
cod_cA1, cod_cH1; ...
cod_cV1, cod_cD1 ...
];
figure('color','k')
image(cod_X);
colormap(hot(256))
axis off % Remove axis ticks and numbers
axis image
figure('color','k')
image(dec2d );
colormap(hot(256))
axis off % Remove axis ticks and numbers
axis image
例如,圖像放在D盤內,名字是brand.jpeg。則命令:
info = imfinfo('brand.jpeg');
用來查看圖像的屬性:
方法以下:
>> clear
>> a=[1 2 3 4 5 6 7 8 9 10]
a =
1 2 3 4 5 6 7 8 9 10
>> a(ones(1,6),:)
ans =
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
>>
要同時讀取這5個txt文件,每個文件中有347(不是500了)個0到1之間的隨機浮點數。對於每個文件,以其中的347個數據做爲y值,以0到346做爲x值,在二維座標系中畫出相對應的點。5個文件,所以有5個圖片,每個圖片都是有347個相對應的點。同時讀取5個文件,因此也要同時生成5個圖片。
clc;clear;
filename = textread('list.txt','%s');
k = length(filename);
for ii = 1:k
y(ii)=str2double(filename{ii});
% eval(['Data_', num2str(ii), '=D']);
end
x=1:k;
plot(x,y,'marker','.','markersize',12);
for ii=1:k
line([x(ii) x(ii)],[y(ii) 0]);
end
function transnumber()
hf=figure('color',[0,1,1],'position',[100,200,400,200],'Name','Êýֵת»¯','Numbertitle','off','menubar','none');
uicontrol(hf,'style','text','units','normalized','position',[0.05,0.8,0.45,0.1],'horizontal','center','string','ÊäÈë¿ò','back',[0,1,1]);
uicontrol(hf,'style','text','units','normalized','position',[0.5,0.8,0.45,0.1],'horizontal','center','string','Êä³ö¿ò','back',[0,1,1]);
uicontrol(hf,'style','frame','units','normalized','position',[0.04,0.33,0.45,0.45],'back',[0,1,1]);
uicontrol(hf,'style','text','units','normalized','position',[0.05,0.6,0.25,0.1],'horizontal','center','string','Ê®½øÖÆÊý','back',[0,1,1]);
uicontrol(hf,'style','text','units','normalized','position',[0.05,0.4,0.25,0.1],'horizontal','center','string','2--16½øÖÆ','back',[0,1,1]);
he1=uicontrol(hf,'style','edit','units','normalized','position',[0.25,0.6,0.2,0.1],'back',[0,1,0],'string','10');
he2=uicontrol(hf,'style','edit','units','normalized','position',[0.25,0.4,0.2,0.1],'back',[0,1,0],'string','2');
uicontrol(hf,'style','frame','units','normalized','position',[0.52,0.33,0.45,0.45],'back',[0,1,0]);
ht=uicontrol(hf,'style','text','units','normalized','position',[0.6,0.5,0.3,0.1],'horizontal','center','back',[0,1,0]);
uicontrol(hf,'style','pushbutton','units','normalized','position',[0.18,0.1,0.2,0.12],'string','ת»»','callback',@trdec);
uicontrol(hf,'style','push','units','normalized','position',[0.65,0.1,0.2,0.12],'string','Í˳ö','callback',@myclose);
function dec=trdec(h,event)
n=str2num(get(he1,'string'));
b=str2num(get(he2,'string'));
ch1='0123456789ABCDEF';
k=1;
while n~=0
p(k)=rem(n,b);
n=fix(n/b);
k=k+1;
end
k=k-1;
strdec='';
while k>=1
kb=p(k);
strdec=strcat(strdec,ch1(kb+1:kb+1));
k=k-1;
end
dec=strdec;
set(ht,'string',num2str(dec));
end
function myclose(hobj,event)
close(hf);
end
end
function[t datafile]=readtxt1(filename)
fprintf('
開始讀取
數據,請等待!
\n');
main_path = 'C:\
MATLAB7\data\';%
文件主路徑
file_path =strcat(main_path,num2str(filename)); %
是
信號文件目錄
filelist = dir([file_path '/*.txt*']);
len = length(filelist);
for i = 1 : len
fid= fopen([file_path '\' filelist(i).name],'r'); % read data signal
fidout1 = fopen('C:\MATLAB7\data\xue.txt', 'wt');% matrix data about signal
fidout2 = fopen('C:\MATLAB7\data\shao.txt', 'wt');
for i = 1 : 8
tline = fgetl(fid);
[s1 s2] = strread(tline, '%s %s', 'delimiter', '=');
Tou{i} = cell2mat(s2);
fprintf(fidout1, cell2mat(s2));
fprintf(fidout1, '\n');
end
while ~feof(fid)
tline = fgetl(fid);
fprintf(fidout2, tline);
fprintf(fidout2, '\n');
end
fclose(fid);
fclose(fidout1);
fclose(fidout2);
shao=load( 'C:\MATLAB7\data\shao.txt');
save C:\MATLAB7\data\shao.mat shao
delete C:\MATLAB7\data\xue.txt
delete C:\MATLAB7\data\shao.txt
load C:\MATLAB7\data\shao.mat
datafile=zeros(size(shao,1),len);
t=shao(i,1);
datafile(:,i)=shao(i,2);
save C:\MATLAB7\data\datafile.mat
end
fprintf('
讀取數據結束。
\n');
clear;clc
filename=input('please input the shot number:');% input form of the shot number like :105871
main_path = 'C:\MATLAB7\data\';%
文件主路徑
file_path =strcat(main_path,num2str(filename)); %
是信號文件目錄
datafile=readtxt1(filename);
names = ls(strcat(file_path,'\', '*.txt'));
name1 = [];
for i = 1 : size(names, 1)
temp = names(i, :);
[a, b] = strread(temp, '%s %s', 'delimiter', '.');
eval([cell2mat(a) '= datafile(:,i)']);
save eval(cell2mat(a))
%temp1 = [na(1:2) na(end)];
%name1 = [name1; temp1];
end
% help ss2tf; ss2t函數。
clc;
clear;
syms a1 a2 a3 b1 b2 b3 c1 c2 d1 s;%定義符號變量
A=[a1 b1;a2 b2];
A=eval(A);
B=[a3;b3];
C=[c1 c2];
D=[d1];
h=simple(C*inv(s*eye(2)-A)*B+D);
pretty(h)
一、方法1:
clc;
clear;
x=randperm(400);
x=mod(x,9);
reshape(x,20,20)
二、方法2:randint(20,20,[0 8])
for j = 1:100
x=1:j;
y=sin(x);
plot(x,y);
F(j) = getframe;
end
pause(1);
movie(F,100);% 播放視頻200次
用下面的方法:把你的文件名放在紅色字體標註的語句裏,fname={'list.txt','rand.txt',.......};能夠所有放入,
而後用下面的代碼做圖:
方法一:
clc;clear;
fname={'list.txt','rand.txt'};
num=size(fname,2);
for ii=1:num
filename = textread(fname{ii},'%s');
k = length(filename);
for ii = 1:k
y(ii)=str2double(filename{ii});
% eval(['Data_', num2str(ii), '=D']);
end
figure(ii);
x=1:k;
plot(x,y,'marker','.','markersize',12);
for ii=1:k
line([x(ii) x(ii)],[y(ii) 0]);
end
end
方法二:
clc;clear;
a=dir('*.txt');
n=length(a); %
須要讀取文件的個數
for i=1:n
name=a(i).name;
filename = textread(name,'%s');
k = length(filename);
for ii = 1:k
y(ii)=str2double(filename{ii});
end
figure('name',name);
x=1:k;
plot(x,y,'marker','.','markersize',12);
for ii=1:k
line([x(ii) x(ii)],[y(ii) 0]);
end
end
方法三:
clc;clear;
a=dir('*.txt'); %讀取全部的.dat文件,如 不是dat文件換一下便可
n=length(a); %須要讀取文件的個數
for i=1:n
datay=load(a(i).name);
k = length(datay);
y=datay;
x=1:k;
plot(x,y,'marker','.','markersize',12);
for ii=1:k
line([x(ii) x(ii)],[y(ii) 0]);
end
title(a(i).name,'FontSize',20);
filename=deblank(strrep(a(i).name, '.txt', '')); %使圖形的名稱和數據的名字一致
saveas(gcf,filename,'jpg') %保存當前圖形
figure
end
1、 啓動
% 獲取當前文件所在路徑
currPath = fileparts(mfilename('fullpath'));
% 切換工做路徑到當前位置
cd(currPath);
% 判斷所用操做系統
if computer == 'PCWIN'
% MATLAB版本號
v = version;
if v(1)~='7'
warndlg ('Only run in matlab 7.x(R14.x)');
return
else
% 添加當前路徑下的全部子目錄
addpath(genpath(pwd));
addpath(genpath(currPath));
end
end
2、 在GUI中使用Axes控件
% 1.刪除全部畫線及對應圖例
% 查找Axes控件中的畫線
sameLines = findobj('type','line');
% 逐一刪除這些畫線
for i = 1 :length(sameLines)
delete(sameLines(i))
end
% 獲取Axes控件中的圖例(因爲畫線所有被刪除,所以爲空)
lgStr = get(legend(handles.ResultsAxes), 'String');
% 從新設置圖例(爲空)
legend(handles.ResultsAxes,lgStr);
% 2.添加畫線
% 獲取原來的圖例
lgStr = get(handles.hLegend, 'String');
% 設置下一個畫線爲添加方式
set(handles.ResultsAxes, 'Nextplot', 'add');
% 指定要畫線的Axes
axes(handles.ResultsAxes);
% 畫線
plot(distance_target, '-r')
% 添加圖例
handles.hLegend = legend(handles.ResultsAxes, lgStr,'目標距離');
% 3.刪除某一畫線
% 所刪除畫線對應的數據爲distance_target,獲取它的句柄
sameLines = findobj('type','line','YData', distance_target);
% 刪除畫線
if ~isempty(sameLines)
delete(sameLines);
end
% 獲取原有的圖例
lgStr = get(legend(handles.ResultsAxes), 'String');
% 從原有圖例中刪除對應圖例
legend(handles.ResultsAxes, setdiff(lgStr, {'目標距離'}));
3、 在GUI中使用Excel表格(Activex控件Microsoft Office Spreedsheet)
% 獲取如今使用的spreedsheet的句柄
ActiveSheet = get(handles.activex1,'ActiveSheet');
% 如今使用的spreedsheet的如今使用工做薄
ActiveWorkbook = get(handles.activex1,'ActiveWorkbook');
% 如今使用的表
eSheets = handles.activex1.ActiveWorkbook.Sheets;
% 使用表的第一個子表
eSheet1 = eSheets.get('Item', 1);
% 激活該表
eSheet1.Activate;
% 獲取當前單元格的句柄
ActiveCell = get(handles.activex1, 'ActiveCell');
% 選擇座標爲A1的單元格
Select(Range(ActiveSheet,'A1'));
% 獲取當前單元格的句柄
ActiveCell = get(handles.activex1, 'ActiveCell');
% 設置當前單元格中的內容
set(ActiveCell, 'Value', '仿真結果報告');
例如,給定區域[x y width height],則隨機取點的程序爲:
x = x + width * rand(1);
y=y+height*rand(1);
我剛剛上手學習matlab這個功能,有些疑惑。好比我在popmenu裏輸入了數據,而且轉化成double型了,可是我在後面的程序裏確沒法調用這個數據,conmmand命令框裏能顯示這個數據的值,可是workspace裏確沒有~~~。怎麼把這個數據讀到workspace裏面去?
先用assignin命令,把數據存到workspace,再用evalin調用。
assignin:
Assign value to variable in specified workspace
Syntax。
assignin(ws, 'var', val)
evalin
Execute MATLAB? expression in specified workspace
Syntax:
evalin(ws, expression)
[a1, a2, a3, ...] = evalin(ws, expression
v = evalin('base', 'var');
t=linspace(0,2*pi,1000);
A=1;
x=A*cos(2*t) + 2*A*cos(t);
y=A*sin(2*t) + 2*A*sin(t);
plot(x,y)
fill(x,y,'r')
axis square
已知點的座標a=[0.3536,1.1036];組成線段的兩個點的座標分別爲b=[0.7071,0.5],c=[0,1]
該如何求出點a到線段bc的垂直距離?
方法1、
clc;
clear;
format long
a=[0.3536,1.1036];
b=[0.7071,0.5];
c=[0,1];
ab=sqrt((a(1,1)-b(1,1))^2+(a(1,2)-b(1,2))^2);
ac=sqrt((a(1,1)-c(1,1))^2+(a(1,2)-c(1,2))^2);
bc=sqrt((c(1,1)-b(1,1))^2+(c(1,2)-b(1,2))^2);
cos_theta=(ab^2+bc^2-ac^2)/(2*ab*bc);
juli=ab*sqrt(1-cos_theta*cos_theta);
line([a(1,1) b(1,1)],[a(1,2) b(1,2)]);
line([a(1,1) c(1,1)],[a(1,2) c(1,2)]);
line([c(1,1) b(1,1)],[c(1,2) b(1,2)]);
bd=ab*cos_theta;
cos_theta2=(b(1,1)-c(1,1))/bc;
dx=b(1,1)-bd*cos_theta2;
dy=b(1,2)+bd*sqrt(1-cos_theta2*cos_theta2);
line([dx a(1,1)],[dy a(1,2)]);
ad=sqrt((a(1,1)-dx)^2+(a(1,2)-dy)^2);
str=sprintf('juli=%f,dx=%f,dy=%f',juli,dx,dy);
disp(str);
juli=0.288741,dx=0.186894,dy=0.867845
>>
方法2、解方程
clear,clc,close all;
a=[0.3536,1.1036];
b=[0.7071,0.5];
c=[0,1];
syms x y;
%---------------------------------------------------------
%
求解部分
,
解方程
,
設垂點
D(x,y)
f1=(y-b(2))./(x-b(1))-(c(2)-b(2))./(c(1)-b(1)); %
斜率
Kbd=Kbc
f2=((y-a(2))./(x-a(1))).*((c(2)-b(2))./(c(1)-b(1)))+1; %
斜率
Kad*Kbc=-1;
[x,y]=solve(f1,f2);x=double(x),y=double(y) %
解出垂點
座標
x y
d=sqrt((x-a(1)).^2+(y-a(2)).^2) %
求垂線距離
%--------------------------------------------------------------
%
繪圖部分
plot([b(1),c(1)],[b(2),c(2)]);
hold on;
plot(a(1),a(2),'ro','linewidth',5);
plot(x,y,'ro','linewidth',5);
plot([a(1),x],[a(2),y],'k','linewidth',3);
axis([-0.1,0.8,0.4,1.2]);
axis equal
str=strcat('\leftarrow
距離
d=',num2str(d));
text((x+a(1))/2+0.01,(y+a(2))/2,str);
text(a(1)+0.02,a(2),'A','fontsize',15);
text(b(1)+0.01,b(2),'B','fontsize',15);
text(c(1)-0.03,c(2),'C','fontsize',15);
text(x-0.02,y-0.03,'D','fontsize',15);
方法三:
clear;clc;
a=[0.3536,1.1036];
b=[0.7071,0.5];
c=[0,1];
k=(b(2)-c(2))/(b(1)-c(1));
b=b(2)-k*b(1);
d=abs(k*a(1)-a(2)+b)/sqrt(k^2+1);
方法4、三維空間中點的座標
clear;clc;
a=[1,0,0],b=[0,1,1],c=[0,0,2];
line([a(1,1) b(1, 1)],[a(1,2) b(1, 2)],[a(1,3) b(1, 3)]);
line([a(1,1) c(1, 1)],[a(1,2) c(1, 2)],[a(1,3) c(1, 3)]);
line([c(1,1) b(1, 1)],[c(1,2) b(1, 2)],[c(1,3) b(1, 3)]);
xlabel('x');ylabel('y');zlabel('z');
text(1,0,0,'a');
text(0,1,1,'b');
text(0,0,2,'c');
grid on
view(3)
ab=sqrt((a(1,1)-b(1,1))^2+(a(1,2)-b(1,2))^2+(a(1,3)-b(1,3))^2);
ac=sqrt((a(1,1)-c(1,1))^2+(a(1,2)-c(1,2))^2+(a(1,3)-c(1,3))^2);
bc=sqrt((c(1,1)-b(1,1))^2+(c(1,2)-b(1,2))^2+(c(1,3)-b(1,3))^2);
cos_theta=(ac^2+ab^2-bc^2)/(2*ac*ab);
cd=ac*sqrt(1-cos_theta*cos_theta);
ad=ab*cos_theta;
sin_theta2=b(1,3)/ab;
adxy=ad*sqrt(1-sin_theta2*sin_theta2);
adx=1-ad*cos(pi/4);
ady=ad*sin(pi/4);
adz=ad/ab;
str=sprintf('cd=%f,dx=%f,dy=%f,dy=%f',cd,adx,ady,adz);
disp(str)
結果:
cd=1.414214,dx=0.051317,dy=0.948683,dy=0.774597
ezplot('25*exp(-(((x-50)/0.2)^2))',[1 100]);
set(gca,'xlim',[30 70]);
matlab做圖時,如何只保存圖像而不顯示圖像(因批量做圖,不用一張一張顯示出來,直接保存就能夠了)?
for ii=1:10
h=figure(ii);
x=0:0.01:ii;
y=sin(x);
plot(x,y);
set(h,'visible','off'); %不用顯示圖像
str=sprintf('figure(%d)',ii); %把圖像保存爲JPG格式的圖片文件
saveas(h,str,'jpg');
end
figure(1);
[x y]=meshgrid(0:0.01:1);
z=peaks(101);
mesh(x,y,z);
set(gca,'ztick',[],'box','off');
grid on
hold on
[x1 z1]=meshgrid(0:0.01:1,-10:0.2:10);%作垂直於y軸,在y=1處的平面
y1=ones(101);
mesh(x1,y1,z1,'edgecolor',[0.8 0.8 0.8],'facecolor',[0.8 0.8 0.8]);
[y1 z1]=meshgrid(0:0.01:1,-10:0.2:10); %作垂直於x軸,在x=1處的平面
x1=ones(101);
mesh(x1,y1,z1,'edgecolor',[0.8 0.8 0.8],'facecolor',[0.8 0.8 0.8]);
A=[ 1 ];
B=[2,3];
C=[4,5;6,7];
D{1}=A;
D{2}=B;
D{3}=C;
>> clear
>> A=[ 1 ]
B=[2,3]
C=[4,5;6,7]
D{1}=A;
D{2}=B
D{3}=C
A =
1
B =
2 3
C =
4 5
6 7
D =
[1] [1x2 double]
D =
[1] [1x2 double] [2x2 double]
>> D{1}
ans =
1
>> D{2}
ans =
2 3
>> D{3}
ans =
4 5
6 7
>>
好比有一個矩陣
1 2
3 4
我想把他擴展成
0 0 0 0
0 1 2 0
0 3 4 0
0 0 0 0
一個通用函數的形式,名稱爲mat2mat,輸入任意矩陣a,就能夠返回你想要的結果。
function b=mattomat(a)
[m n]=size(a);
b=zeros(m+2,n+2);
b(2:m+1,2:n+1)=a;
示例:
>> a=[1 2 3 4 5 6;1 2 3 4 5 6;1 2 3 4 5 6]
a =
1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5 6
>> mat2mat(a)
ans =
0 0 0 0 0 0 0 0
0 1 2 3 4 5 6 0
0 1 2 3 4 5 6 0
0 1 2 3 4 5 6 0
0 0 0 0 0 0 0 0
>>
首先,設置x軸和y軸的xlim和ylim屬性值,譬如爲[0 100]和[0 50];
而後,再windowbuttonmotionFcn中用以下代碼:
pos=get(gca,'currentpoint'); %
取得鼠標當前的座標值
if pos(1,1)>=0&&pos(1,1)<=100&&pos(1,2)>=0&&pos(1,2)<=50%
判斷是否在
axes1
內,若是在其中,則顯示座標值。
set(handles.edit1,'string',num2str(pos(1,1)));
set(handles.edit2,'string',num2str(pos(1,2)));
end
G=tf(2.25,[2756.25,105,1],'inputdelay',5);
h=figure(1);
axes();
step(G);
title('¿ª»·½×Ô¾ÏìÓ¦ÇúÏß');
xlabel('time');
ylabel('step response');
grid
K=2.25;T=50,tao=105;
num=2.25;
den=[2756.25 105 1];
G=tf(num,den);
s=tf('s');
%P
PKp=T/(K*tao);
Gk1=PKp*G;
sys1=feedback(Gk1,1,-1);
figure(2);
axes();
step(sys1);
title('P¿ØÖƽ×Ô¾ÏìÓ¦ÇúÏß');
xlabel('time');
ylabel('step response');
%PI
PIKp=0.9*T/(K*tao);
PITi=3*tao;
Gc2=PIKp*(1+1/(PITi*s));
Gk2=Gc2*G;
sys2=feedback(Gk2,1,-1);
figure(3);
axes();
step(sys2);
title('PI¿ØÖƽ×Ô¾ÏìÓ¦ÇúÏß');
xlabel('time');
ylabel('step response');
hold on
%PID
PIDKp=1.2*T/(K*tao);
PIDTi=2*tao;
PIDTd=0.5*tao;
Gc3=PIKp*(1+1/(PIDTi*s)+PIDTd*s);
Gk3=Gc3*G;
sys3=feedback(Gk3,1,-1);
figure(4);
axes();
step(sys3);
title('PID¿ØÖÆÏìÓ¦ÇúÏß');
xlabel('time');
ylabel('response');
matlab 2008a或matlab 2009a環境下,figure的某些隱藏屬性進行了優化。
【MATLAB GUI設計學習手記】中講到,root對象有一個很重要的未公開屬性:HideUndocumented(默認值爲on)。該屬性的做用是隱藏一些matlab不想讓你們知道的屬性。顯示未公開的屬性,使用如下命令:
set(0,'HideUndocumented','off')
此時,能夠用get(figure)命令查看figure的全部屬性(包括未公開的屬性)了。
對於root對象的未公開屬性,書中已經講了,這裏講一下figure對象的一個未公開屬性:JavaFrame。該屬性在使用時會彈出警告:JavaFrame可能會在新的matlab版本中廢棄。要關閉該警告,須要先在matlab 2009a命令行輸入下列命令:
warning('off','MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame');
如今研究一下JavaFrame屬性。
首先,在matlab 2009a命令行輸入下列命令:
h=figure;
javaFrame = get(h,'JavaFrame');
get(javaFrame)
命令行輸出以下:
UIControlBackgroundCompatibilityMode: 0
ActiveXCanvas: []
AxisComponent: [1x1 com.mathworks.hg.peer.FigureAxisComponentProxy$_AxisCanvas]
Class: [1x1 java.lang.Class]
Debug: 0
Desktop: [1x1 com.mathworks.mde.desk.MLDesktop]
ExposeEvents: []
FigureIcon: [1x1 javax.swing.ImageIcon]
FigurePanelContainer: [1x1 com.mathworks.hg.peer.FigurePanel$2]
GroupName: 'Figures'
Maximized: 0
Minimized: 0
MouseWheelCallback: [1x1 com.mathworks.jmi.Callback]
NativeChildWindowHandle: 0
NativeWindowHandle: 0
NotificationSuccessor: []
UserLastMethodID: 23
UserParentFigure: [1x1 com.mathworks.hg.peer.FigurePeer]
(1)FigureIcon子屬性。從字面就知道該屬性是設置figure的圖標。而其值爲: [1x1 javax.swing.ImageIcon]。所以,改變圖標的方法以下:
複製內容到剪貼板
代碼:
set(javaFrame,'FigureIcon',javax.swing.ImageIcon('icon.jpg')) %icon.jpg爲指定的圖標
(2)Maximized子屬性。該值設置爲1時表示窗口最大化。如:
複製內容到剪貼板
代碼:
set(javaFrame,'Maximized',1)
(3)Minimized子屬性。該值設置爲1時表示窗口最小化。如:
複製內容到剪貼板
代碼:
set(javaFrame,'Minimized',1)
固然,若要窗口置頂,只須要設置figure的WindowStyle屬性爲modal。
值得注意的是,最大化屬性Maximized在GUIDE建立的GUI中彷佛並很差用。
filename={};
for i=1:50
fname=strcat('image',num2str(i),'.mat');
filename=[filename;cellstr(fname)];
end
在edit text中輸入數學表達式,如sin(t),點擊push button,能夠在axes中顯示圖形。
代碼:
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
user_string = get(handles.edit1,'String') ;
str=user_string{1};
syms t
x=0:0.01:8;
y1=sym(str);
y=subs(y1,t,x);
axes(handles.axes1)
plot(x,y);
繪前篇用「Grads平均值輸出到硬盤」日誌,這裏就是用MATLAB來繪折線圖。平時用MATLAB很少,所以編寫編看幫助文檔,整理了一些有用的註記寫在這裏備忘,也供朋友借鑑。這段M文件註記幾點:
一、 MATLAB如何從硬盤讀取文件。
二、 如何微調subplot子圖的位置。
三、 plot命令繪曲線時,曲線上的標誌如何調整大小。
四、 座標軸的調整。
五、 box on命令
六、 座標標題中如何標上標。
七、 如何調整圖示(legend)的位置。
八、 以上內容在MATLAB幫助文檔中有更詳細內容。這裏的代碼只是我實用中的一個例子。代碼以下,紅色字體爲日誌註記,非代碼一部分。
clear;
%----------------------------------------------
% NH Radiative Effect Mod-Noall
讀取硬盤有格式文件數據的寫法。
fid_bc=fopen('D:\_CurrentPaper\RadiativeForcing\ModNoall_NH\bc.dat','r');
bc = fscanf( fid_bc, '%f', [1,12]);
fclose( fid_bc );
fid_nit=fopen('D:\_CurrentPaper\RadiativeForcing\ModNoall_NH\nit.dat','r');
nit = fscanf( fid_nit, '%f', [1,12]);
fclose( fid_nit );
fid_sul=fopen('D:\_CurrentPaper\RadiativeForcing\ModNoall_NH\sul.dat','r');
sul = fscanf( fid_sul, '%f', [1,12]);
fclose( fid_sul );
fid_poa=fopen('D:\_CurrentPaper\RadiativeForcing\ModNoall_NH\poa.dat','r');
poa = fscanf( fid_poa, '%f', [1,12]);
fclose( fid_poa );
fid_soa=fopen('D:\_CurrentPaper\RadiativeForcing\ModNoall_NH\soa.dat','r');
soa = fscanf( fid_soa, '%f', [1,12]);
fclose( fid_soa );
%----------------------------------
這裏要畫一個2*2共4幅子圖。先將第1個子圖的位置調整。
h = subplot( 2, 2, 1, 'replace' );先讓MATLAB默認繪製第1幅子圖,h是子圖1的句柄
po = get( h, 'Position' );get命令從句柄h中獲取'Position'的內容,返回一個含4個元素的一維數組放到po中。這4個元素分別是子圖1的left, bottom, width, height。
subplot( 2, 2, 1, 'replace' );從新繪製子圖1
subplot('Position',[po(1)+0.03,po(2)-0.03,po(3),po(4)]);
子圖1的新位置能夠這樣調整
%----------------------------------
box on;box on命令使得子圖在top、right皆繪製座標軸。這樣比較好看,見國外不少文獻中的圖都是這樣畫的。
hold on;
axis([0 13 -3 2]);
set( gca, 'XTick', [1:12] );gca表示當前對象句柄,set命令分別對當前對象(即子圖1)設置座標軸XTick和YTick屬性。這兩個屬性分別表示了座標軸的實際繪值範圍。
set( gca, 'YTick', [-3:1:2] );
title( 'The North Hemisphere' );
plot( 1:12, bc, '-r.', 'MarkerSize', 10 );子圖1中第1條曲線用實線繪,帶有圓點,紅色。MarkerSize屬性設置圓點的大小是10。這樣畫出來的就是實心圓了。
plot( 1:12, nit, '-b.', 'MarkerSize', 10 );
plot( 1:12, sul, '-g.', 'MarkerSize', 10 );
plot( 1:12, poa, '-m.', 'MarkerSize', 10 );
plot( 1:12, soa, '-k.', 'MarkerSize', 10 );
%zeroArr = zeros( 14 );
%plot( 0:13, zeroArr, '--k' )
xlabel( 'Month' );
ylabel( 'Radiative Effect (Wm^-^2)' );單位裏有上標,^表示後續一個字符爲上標。
下述代碼繪子圖二、三、4,雷同。
%-----------------------------------
% NH Radiative Forcing Fut-Mod 子圖2
fid_bc=fopen('D:\_CurrentPaper\RadiativeForcing\FutMod_NH\bc.dat','r');
bc = fscanf( fid_bc, '%f', [1,12]);
fclose( fid_bc );
fid_nit=fopen('D:\_CurrentPaper\RadiativeForcing\FutMod_NH\nit.dat','r');
nit = fscanf( fid_nit, '%f', [1,12]);
fclose( fid_nit );
fid_sul=fopen('D:\_CurrentPaper\RadiativeForcing\FutMod_NH\sul.dat','r');
sul = fscanf( fid_sul, '%f', [1,12]);
fclose( fid_sul );
fid_poa=fopen('D:\_CurrentPaper\RadiativeForcing\FutMod_NH\poa.dat','r');
poa = fscanf( fid_poa, '%f', [1,12]);
fclose( fid_poa );
fid_soa=fopen('D:\_CurrentPaper\RadiativeForcing\FutMod_NH\soa.dat','r');
soa = fscanf( fid_soa, '%f', [1,12]);
fclose( fid_soa );
%----------------------------------
h = subplot( 2, 2, 3, 'replace' );
po = get( h, 'Position' );
subplot( 2, 2, 3, 'replace' );
subplot( 'Position', [po(1)+0.03, po(2)+0.03, po(3), po(4)]);
%----------------------------------
box on;
hold on;
axis([0 13 -3 2]);
set( gca, 'XTick', [1:12] );
set( gca, 'YTick', [-3:1:2] );
%title( 'NH Fut-Mod' );
plot( 1:12, bc, '-r.', 'MarkerSize', 10 );
plot( 1:12, nit, '-b.', 'MarkerSize', 10 );
plot( 1:12, sul, '-g.', 'MarkerSize', 10 );
plot( 1:12, poa, '-m.', 'MarkerSize', 10 );
plot( 1:12, soa, '-k.', 'MarkerSize', 10 );
%zeroArr = zeros( 14 );
%plot( 0:13, zeroArr, '--k' )
xlabel( 'Month' );
ylabel( 'Radiative Forcing (Wm^-^2)' );
%------------------------------------
% SH Radiative Effect Mod-Noall 子圖3
fid_bc=fopen('D:\_CurrentPaper\RadiativeForcing\ModNoall_SH\bc.dat','r');
bc = fscanf( fid_bc, '%f', [1,12]);
fclose( fid_bc );
fid_nit=fopen('D:\_CurrentPaper\RadiativeForcing\ModNoall_SH\nit.dat','r');
nit = fscanf( fid_nit, '%f', [1,12]);
fclose( fid_nit );
fid_sul=fopen('D:\_CurrentPaper\RadiativeForcing\ModNoall_SH\sul.dat','r');
sul = fscanf( fid_sul, '%f', [1,12]);
fclose( fid_sul );
fid_poa=fopen('D:\_CurrentPaper\RadiativeForcing\ModNoall_SH\poa.dat','r');
poa = fscanf( fid_poa, '%f', [1,12]);
fclose( fid_poa );
fid_soa=fopen('D:\_CurrentPaper\RadiativeForcing\ModNoall_SH\soa.dat','r');
soa = fscanf( fid_soa, '%f', [1,12]);
fclose( fid_soa );
%----------------------------------
h = subplot( 2, 2, 2, 'replace' );
po = get( h, 'Position' );
subplot( 2, 2, 2, 'replace' );
subplot( 'Position', [po(1)-0.03, po(2)-0.03, po(3), po(4)]);
%----------------------------------
box on;
hold on;
axis([0 13 -1.2 0.8]);
set( gca, 'XTick', [1:12] );
set( gca, 'YTick', [-1.2:0.4:0.8] );
title( 'The South Hemisphere' );
plot( 1:12, bc, '-r.', 'MarkerSize', 10 );
plot( 1:12, nit, '-b.', 'MarkerSize', 10 );
plot( 1:12, sul, '-g.', 'MarkerSize', 10 );
plot( 1:12, poa, '-m.', 'MarkerSize', 10 );
plot( 1:12, soa, '-k.', 'MarkerSize', 10 );
%zeroArr = zeros( 14 );
%plot( 0:13, zeroArr, '--k' )
xlabel( 'Month' );
%ylabel( 'Radiative Effect (Wm^-^2)' );
%-------------------------------------------
% SH Radiative Forcing Fut-Mod 子圖4
fid_bc=fopen('D:\_CurrentPaper\RadiativeForcing\FutMod_SH\bc.dat','r');
bc = fscanf( fid_bc, '%f', [1,12]);
fclose( fid_bc );
fid_nit=fopen('D:\_CurrentPaper\RadiativeForcing\FutMod_SH\nit.dat','r');
nit = fscanf( fid_nit, '%f', [1,12]);
fclose( fid_nit );
fid_sul=fopen('D:\_CurrentPaper\RadiativeForcing\FutMod_SH\sul.dat','r');
sul = fscanf( fid_sul, '%f', [1,12]);
fclose( fid_sul );
fid_poa=fopen('D:\_CurrentPaper\RadiativeForcing\FutMod_SH\poa.dat','r');
poa = fscanf( fid_poa, '%f', [1,12]);
fclose( fid_poa );
fid_soa=fopen('D:\_CurrentPaper\RadiativeForcing\FutMod_SH\soa.dat','r');
soa = fscanf( fid_soa, '%f', [1,12]);
fclose( fid_soa );
%----------------------------------
h = subplot( 2, 2, 4, 'replace' );
po = get( h, 'Position' );
subplot( 2, 2, 4, 'replace' );
subplot( 'Position', [po(1)-0.03, po(2)+0.03, po(3), po(4)]);
%----------------------------------
box on;
hold on;
axis([0 13 -1.2 0.8]);
set( gca, 'XTick', [1:12] );
set( gca, 'YTick', [-1.2:0.4:0.8] );
%title( 'SH Fut-Mod' );
plot( 1:12, bc, '-r.', 'MarkerSize', 10 );
plot( 1:12, nit, '-b.', 'MarkerSize', 10 );
plot( 1:12, sul, '-g.', 'MarkerSize', 10 );
plot( 1:12, poa, '-m.', 'MarkerSize', 10 );
plot( 1:12, soa, '-k.', 'MarkerSize', 10 );
%zeroArr = zeros( 14 );
%plot( 0:13, zeroArr, '--k' )
xlabel( 'Month' );
%ylabel( 'Radiative Forcing (Wm^-^2)' );
我將legend放在了子圖4上。
gca=legend( 'BC', 'Nitrate', 'Sulfate', 'POA', 'SOA', 4 );
4表示把legend放在子圖的右下角,還有幾個數字的含義是:
0 = Automatic "best" placement (least conflict with data)
1 = Upper right-hand corner (default)
2 = Upper left-hand corner
3 = Lower left-hand corner
4 = Lower right-hand corner
-1 = To the right of the plot
po=get( gca, 'Position' ); 發現這樣放置後legend要擋住圖,所以須要再微調一下。得到legend的'Position'值。
set( gca, 'FontSize', 8, 'Position', [po(1)-0.01, po(2)+0.01, po(3), po(4)] ); 從新設置legend的位置,同時設置legend裏面的字體爲8號。
legend('boxoff');不畫legend的外框。
強調的是上述調整legend的值要不斷地試。由於legend相對子圖的位置還要隨畫圖窗口大小變化而變化。若是你看不懂這句,試試就知道了。
畫了一個三維圖,想在這個圖上用一個豎着的條 兩端表示出z的最小值和最大值 及其中間的一些數值。
[x y]=meshgrid(0:0.1:10);
z=peaks(101);
mesh(x,y,z);
minZ=min(min(z));
maxZ=max(max(z));
str1=sprintf('%f',minZ);
str2=sprintf('%f',maxZ);
colorbar('YTickLabel',...
{str1,'','','','','','',str2})
在處理第一個文件時,產生了
handles.a.a
handles.a.b
handles.b
handles.c
....
等N個變量。
處理完成後。打開第二個文件時,發現這些變量還一直存在。
這致使對第二個文件處理的失敗。
在打開第二個文件,調用function openavi_Callback(hObject, eventdata, handles)時
handles.a.a
handles.a.b
handles.b
handles.c
....
等N個變量依然存在。
請問有什麼命令能夠較簡單的把這些變量一次清除掉。但願不用在function openavi_Callback(hObject, eventdata, handles)以前
打n句clear handles.a,handles.b....
解決辦法:
在處理第一個文件的前面,用下面的語句:
handlesOld=guidata(hObject);%
取得
handles
結構的最初值,並保存
handles.handlesOld=handlesOld;
guidata(hObject,handles);
在處理第二個文件的前面,用下面的語句:
handles=handles.handlesOld;%
回覆
handles
結構的值爲文件處理前的初值
guidata(hObject,handles);
注意:以上語句均是在控件的callback中實現的。這樣,中間加在handles結構上的變量都一次性清除了。
如何給元胞中的多個一維向量前增長同一個數?好比:
原cell = { [1 2 3 ];[ 4 5 6 7 ];[6 7]}
要在該cell中每個向量前增長一個9獲得:
cell = { [9 1 2 3 ];[ 9 4 5 6 7 ];[9 6 7]}
用下面的代碼就可實現:
>> clear
>> cell = { [1 2 3 ];[ 4 5 6 7 ];[6 7]}
cell =
[1x3 double]
[1x4 double]
[1x2 double]
>>cell(1)=mat2cell([9 cell2mat(cell(1))])
cell =
[1x4 double]
[1x4 double]
[1x2 double]
>>
或者:
cell{1}=[9 cell{1}];
cell{2}=[9 cell{2}];
cell{3}=[9 cell{3}];
celldisp(cell)
cell{1} =
9 1 2 3
cell{2} =
9 4 5 6 7
cell{3} =
9 6 7
利用matlab的guide來生成GUI程序,界面佈局直觀、方便,缺點就是都須要拖帶一個m文件和fig文件,...。不過,我仍是偏向於這種編程方式,由於要寫的代碼少,符合我這種懶人的習慣,呵呵。
前面有會員提出問題:如何在不一樣的GUI之間相互操做其中的控件?
若是程序是由matlab的GUIDE生成的,處理起來比較簡單。下面就說說個人一點經驗:
每一個GUI程序都生成一個handles結構,該handles結構和該GUI是緊密關聯的。handles結構中儲存了該GUI中figure以及全部控件(pushbutton、edit、statictext、slider、axes、table、等等)的句柄。咱們知道,matlab提供了利用句柄來操做句柄所對應的對象的方法,就是set和get函數。
對handles結構的更新和得到是經過guidata函數來實現的。guidata函數的原型在help中有明確的定義:
guidata(object_handle,data);%保存與object_handle相關聯的結構data
data = guidata(object_handle);%取得與object_handle相關聯的結構,並賦值給data
所以,利用guidata來取得與GUI相關聯的handles結構,就間接地取得了其中控件的句柄,利用該句柄,並用set和get函數就能夠實現對控件的操做。
例如:設計兩個GUI界面,實現經過一個界面的PUSHBUTTON設置另外一個界面中EDIT的值,兩個界面是同時打開着的。
一、這個問題是主GUI操做從GUI中的控件的問題
能夠這樣來實現:
假設兩個GUI分別爲gui1和gui2,在gui1中有button1,在gui2中有edit1。在gui1的pushbutton中gui2並顯示,而後設置gui2中的edit中的值爲想要的數值:
在gui1 的button1的callback中用如下代碼:
hGUI2=gui2();%打開gui2,同時取得gui2的figure的句柄
handles_of_gui2=guidata(hGUI2);%利用gui2的figure的句柄,經過guidata,獲得其handles結構
set(handles_of_gui2.edit1,'string','content from gui1!');%利用獲得的handles結構取得gui2中的eidt1的句柄,並用set設定其數值
二、如何實如今從GUI中操做主GUI中的控件呢?即在gui2中操做gui1中的控件
假設gui1中也有一個edit控件,tag爲edit2,在gui2中也有一個button,‘tag’爲button2。實如今gui2中用button2來設置
gui1中的edit2的數值,方法以下:
(1)在gui1的button1的callback中用下面的語句:
hGUI2=gui2(handles.figure1);%把gui1的figure的句柄傳給gui2
%其它語句不變
(2)在gui2的OpeningFcn函數中用下面的語句:
handles_of_gui1=guidata(varargin{1});%取得和figure1相關聯的gui1的handles結構
handles.handles_of_gui1=handles_of_gui1;
guidata(hObject,handles);%把handles_of_gui1保存到gui2的handles結構中,以方便gui2的其它callback調用
(3)在gui2的button2的callback函數中:
mainhandles=handles.handles_of_gui1;
set(mainhandles.edit2,'string','content from gui2!');
從以上能夠看出,handles結構實際上是爲用戶提供了一種比較方便的在不一樣gui之間共享數據的方法。
若將 figure 窗口的 Toolbar 屬性設置爲 figure,則能夠出現 Matlab 圖形工具條,裏面包括文件打開保存,圖象放大、縮小等按鈕。但實際使用過程當中可能用不了這麼多功能,須要將其中的一些按鈕刪除。那麼就能夠採用下面的函數保留咱們想要的按鈕:
function KeepToolbarButton(fig, keep_reg)
% KEEPTOOLBARBUTTON - customize the figure toolbar
% @param toolbar
% handle of the fig containing toolbar
% @param keep_reg
% the regular expressions for buttons which are to be left
%
% Notice: the tags of the uitoolbar buttons are as follows:
% 'Plottools.PlottoolsOn'
% 'Plottools.PlottoolsOff'
% 'Annotation.InsertLegend'
% 'Annotation.InsertColorbar'
% 'Exploration.DataCursor'
% 'Exploration.Rotate'
% 'Exploration.Pan'
% 'Exploration.ZoomOut'
% 'Exploration.ZoomIn'
% 'Standard.EditPlot'
% 'Standard.PrintFigure'
% 'Standard.SaveFigure'
% 'Standard.FileOpen'
% 'Standard.NewFigure'
% it's curious that findobj won't work here, but `findall' will
toolbar = findall(fig, 'type', 'uitoolbar');
% it's curious that get(toolbar, 'Children') won't work here,
% but `allchild' will
toolbar_children = allchild(toolbar);
for m = 1:size(toolbar_children, 1)
target = get(toolbar_children(m), 'Tag');
match = regexpi(target, keep_reg);
if isempty(match)
set(toolbar_children(m), 'Visible', 'off');
end
end
只要給定匹配按鈕 tag 名稱的正則表達式,就能夠選擇咱們想要的按鈕,例如:
KeepToolbarButton(handles.figure1, '(zoomout)|(zoomin)|(pan)');
>> a = 3.2435;
>> digits(2)
>> vpa(a)
ans =
3.2
>> digits(3)
>> vpa(a)
ans =
3.24
a(find(a(:)<eps))=floor(a(find(a(:)<eps)));
用一條語句就能夠把a矩陣中小於eps的數值取爲0了。
請教一下,如何用matlab畫出被平面截取後的表面圖形。即如圖所示,已經獲得原表面和用於截的平面的相交圖形,如今想獲得截後的表面,請幫幫我哦。
假設爲surfc(x1,y1,z1),截取的平面是z=z0; 可令z1中小於z0的元素等於NaN,大於z0的元素保持不變,而後用surfc從新繪圖。
[X,Y,Z] = peaks(30);
figure(1);
surfc(X,Y,Z);
Z(Z(:)<=1.0)=NaN;
figure(2);
surfc(X,Y,Z);
set(gca,'zlim',[-10 10]);
logo1 = '5.jpg';
figure;
imshow(logo1,'Border','tight')
ii=imread('5.jpg');%5.jpg是256x256的灰度圖,gray image
x=1:256;
figure;
hist(ii,x);
例如R是個24X23的cell結構的矩陣,把其寫入到myfile.txt中:
一、數據寫入:
clc;clear;
BMP= imread('Hehua_BMP88.bmp');%24*32*3的矩陣
[m,n,z]=size(BMP);%m=24,n=32
R={};
for i = 1 : m
for j = 1:n
R{i,j} = dec2hex(BMP(i,j,1),2);%轉換爲十六進制,佔兩位,如3C
end
end
dlmwrite('myfile.txt', R, 'delimiter', '\t');%寫入myfile.txt文件中,若是myfile.txt不存在,則自動建立
二、數據讀取:
t=textread('myfile.txt','%s');%讀取txt文件中的內容
T={};%定義空的cell結構的矩陣
for ii=1:2:length(t)
t1=sprintf('%s%s',t{ii}, t{ii+1}); %把兩位合成爲一個字符串‘3C’
T=[T; cellstr(t1)];%cell矩陣擴展
end
result=reshape(T,24,32);%從新整理成24X32的 cell類型的矩陣
clc;clear;
n=7;
x=zeros(n,n);
maxlen=ceil(n/2)-1;
flag=mod(n,2);
beginnum=5-flag*3;
if flag==1
%奇數陣
x(maxlen+1,maxlen+1)=1;
for i=1:maxlen
x(maxlen+2-i:1:end-maxlen+i,end-maxlen+i)=beginnum:beginnum+2*i-1;
beginnum=beginnum+2*i;
x(end-maxlen+i,end-maxlen+i-1:-1:maxlen+1-i)=beginnum:beginnum+2*i-1;
beginnum=beginnum+2*i;
x(end-maxlen+i-1:-1:maxlen+1-i,maxlen+1-i)=beginnum:beginnum+2*i-1;
beginnum=beginnum+2*i;
x(maxlen+1-i,maxlen+2-i:1:end-maxlen+i)=beginnum:beginnum+2*i-1;
beginnum=beginnum+2*i;
end
else
%偶數陣
x(maxlen+1,maxlen+1:1:maxlen+2)=1:2;
x(maxlen+2,maxlen+1:1:maxlen+2)=4:-1:3;
for i=1:maxlen
x(end-maxlen+i-1:-1:maxlen+1-i,maxlen-i+1)=beginnum:beginnum+2*i;
beginnum=beginnum+2*i+1;
x(maxlen+1-i,maxlen+2-i:1:end-maxlen+i)=beginnum:beginnum+2*i;
beginnum=beginnum+2*i+1;
x(maxlen-i+2:1:end-maxlen+i,end-maxlen+i)=beginnum:beginnum+2*i;
beginnum=beginnum+2*i+1;
x(end-maxlen+i,end-maxlen+i-1:-1:maxlen-i+1)=beginnum:beginnum+2*i;
beginnum=beginnum+2*i+1;
end
end
disp(x)
43 44 45 46 47 48 49
42 21 22 23 24 25 26
41 20 7 8 9 10 27
40 19 6 1 2 11 28
39 18 5 4 3 12 29
38 17 16 15 14 13 30
37 36 35 34 33 32 31
把要標註的曲線的句柄和字符串包含到legend中:
figure(1);
h2=axes('position',[0 0 1 1]);
axis(h2);
x2=0:pi/50:2*pi;
y2=sin(x2);
h3=plot(x2,y2,'b-');
h1=axes('position',[0.3 0.2 0.4 0.4]);
axis(h1);
x1=0:pi/50:2*pi;
y1=cos(x1);
h4=plot(x1,y1,'r-');
hold on
h=[h3; h4];
str=['
大圖中的曲線
';'
小圖中的曲線
'];
legend(h,str);
問題:
1, 若是我一個figure上畫了兩條曲線, 好比一條正弦一條餘弦, 如何才能實現當我把鼠標移到正弦曲線上時, 能顯示出一個註釋框之類的, 說明這是條正弦曲線, 同理移到餘弦曲線上時也能顯示出這樣的註釋框?
2, 相似的問題, 鼠標移動到曲線上某一點時時, 如何才能顯示出這一點的座標呢? 不經過figure的工具欄選擇, 想直接經過鼠標移動到圖上就能顯示座標。 以爲頗有實際意義,因而花點時間編寫程序,初步實現了這個想法。
程序說明:
程序中繪製了兩條曲線,分別是正弦曲線和餘弦曲線(其它曲線的道理是同樣的),當鼠標移動到各條曲線上時,分別顯示曲線的類型以及當前的座標值。
程序中利用了legend以及條件判斷語句。
初始化代碼:OpeningFcn函數
% --- Executes just before fftexpand is made visible.
function fftexpand_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to fftexpand (see VARARGIN)
% Choose default command line output for fftexpand
handles.output = hObject;
x=0:pi/50:2*pi;
y=sin(x);
y1=cos(x);
axes(handles.axes1);
h1=plot(x,y,'color',[1 0 0],'linewidth',2);
hold on
h2=plot(x,y1,'color',[0 0 1],'linewidth',2);
handles.h1=h1; %保存曲線的句柄,供legend函數使用
handles.h2=h2;
% Update handles structure
guidata(hObject, handles);
核心代碼:編輯WindowButtonMotionFcn函數
% --- Executes on mouse motion over figure - except title and menu.
function figure1_WindowButtonMotionFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
h1=handles.h1;
h2=handles.h2; %取得先前保存的句柄
point=get(gca,'currentpoint'); %取得座標軸中當前的座標值
xlim=get(gca,'xlim'); %取得x軸和y軸的最大顯示區域的尺寸
ylim=get(gca,'ylim');
if point(1,1)>0&&point(1,1)<7&&point(1,2)>-1&&point(1,2)<=1%判斷鼠標是否在座標軸顯示的區域
x=point(1,1);y=point(1,2);
y1=sin(x);
y2=cos(x);
str1=sprintf('正弦曲線\n x=%f,y=%f\',x,y1);
str2=sprintf('餘弦曲線©\n x=%f,y=%f',x,y2);
if abs(y1-y)<=abs(y2-y)&&(abs(y1-y)<0.01||abs(y2-y)<0.01)%判斷鼠標是否實在正弦曲線附近
legend(h1,str1,'location','southwest');
elseif abs(y1-y)>abs(y2-y)&&(abs(y1-y)<0.01||abs(y2-y)<0.01) %判斷鼠標是不是在餘弦曲線附近,(abs(y1-y)<0.01||abs(y2-y)<0.01)判斷鼠標是否在曲線附近
legend(h2,str2,'location','southwest');
else
legend('off'); %不然,關閉legend
end
end
代碼一:
clear
clc
[x,y]=cylinder(1:0.2:5,100);
mesh(x,y,1./sqrt(x.^2+y.^2))
代碼二:
%原來在二維時的最小和最大的x值
xmin=1;
xmax=3;
%肯定y的範圍
ymax=1/xmin;
ymin=1/xmax;
[x,z]=meshgrid(-xmax:0.01:xmax);
r=sqrt(x.^2+z.^2);
y=1./r;
%將不在範圍內的值消去
[r,c]=find(y>ymax);
y(sub2ind(size(y),r,c))=NaN;
[r1,c1]=find(y<ymin);
y(sub2ind(size(y),r1,c1))=NaN;
%畫圖
mesh(x,z,y);
hold on
mesh(x,z,-y);
hold off
在Outputfcn函數的最後添加以下語句:
javaFrame = get(gcf,'JavaFrame');
set(javaFrame,'Maximized',1)
就能夠實現GUI窗口一開始便以‘最大化’的形式顯示。
假定在文本框中輸入kkLL,則自動轉化爲快快樂樂。如今假設有不少這樣的待轉換字符對,存於記事本中,在輸入框中一旦「遇到」記事本中的英文代碼,則自動轉換爲對應的中文代碼,若是沒遇到,則不用轉換。
記事本內容舉例以下:
kkll 快快樂樂;ggxx 高高興興;ppaa 平平安安
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
string_edit=get(handles.edit1,'string');
fid=fopen('wo.txt','r');
str=fgetl(fid);
[str1 str2]=strread(str,'%s %s','delimiter',' ');
text=cell(3,2);
text{1,1}=str1;
text{1,2}=str2;
counter=3;
strout='';
while feof(fid)==0
str=fgetl(fid);
[str1 str2]=strread(str,'%s %s','delimiter',' ');
text{counter-1,1}=str1;
text{counter-1,2}=str2;
counter=counter+1;
end
for ii=1:3
if strcmp(text{ii,1},string_edit)
strout=text{ii,2};
end
end
if ~isempty(strout)
set(handles.edit1,'string',strout);
end