目 录 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