1、GUI新手之——教你读懂GUI的M文件... 10

2、GUI程序中改变current directory引起的问题... 15

3、GUI中h0bject和handles 的区别... 16

4、handles结构中句柄和对象的关联问题... 17

5、Matlab利用定时器连续显示图片的问题... 19

5-1、GUI中实现在图片任意位置上标注text. 22

5-2、使用edit的另外一种callback. 22

6、MATLAB 如何实现图像的任意裁减?... 22

7、坐标轴标注刻度、网格、文字方向... 23

8、Matlab中对uitable的操作:调节各列宽度,设定某列是可编辑的... 24

9、将在Matlab下编写的GUI转成独立于Matlab平台的应用程序... 25

10、要将用Matlab语言编写的函数文件编译成可独立执行的*.exe文件... 28

11、matlab GUI程序转换成exe可执行文件... 31

12、gui生成独立的应用程序的发布问题... 33

13、GUI控制simulink模块及参数的综合实例!... 34

13-1、在axes显示图像后,在图像上单击鼠标时,回调函数的定义规则和使用方法... 35

14、如何在循环中加入waitbar,并在waitbar上添加‘取消’按钮... 36

15、在matlab中对信号进行FFT变换... 38

16、动态显示figure中曲线的x-y坐标值的一个函数... 40

17、在GUI界面的打开按钮中,如何对文件进行操作... 42

18、Matlab不同控件之间的数据传递问题... 45

19、在edit box里输入相关数据后,直接按回车键,不用鼠标点击pushbutton 就可以直接执行... 46

19-1 GUI使用editbox输入数据后如何自动清除数据... 46

20、在GUI中,计算结果怎么用excel来保存到指定的文件夹中... 47

21、如何得到popupmenu选项中最后一个字符串的VALUE值... 49

22、回调函数互相调用的问题... 49

22-2string和number相互转换的问题... 50

23、这样的功能的pushbutton的callback怎么写呀,谢谢了... 50

24、GUI中axes使用subplot时的清空及axes大小的固定的解决方法... 51

25、退出GUI时如何把全局变量中的值清空?... 53

26、从串口接受数据时,如何把波形绘制到指定的坐标轴上?... 53

27、两个GUI之间如何传递数据... 55

28-1 几个有用的帖子... 57

28-2、GUI之间互相调用和关闭问题... 60

29、GUI timer定时器... 60

30、如何在循环中加入waitbar. 61

31、如何连续读入图片!!... 62

32、如何把此次输入的值保存为下一次初始化的值... 63

33、Matlab关于解决自动保存gcf的问题... 63

34-1、在matlab里面如何读取excel里面的数据或者写入数据... 65

34-2、在excel中连续输入数据。... 66

35、Matlab GUI不同控件之间的数据传递问题... 68

36、怎么统计一个十进制数中"0"的个数??求助!... 69

37、Matlab对listbox里的条目能否一条条单独设置回调函数?. 70

38、键盘操作:matlab GUI中如何取得从键盘输入的按键的键值... 72

39、GUI如何响应鼠标事件... 73

40、matlab 截图、图像处理... 76

41、MATLAB GUI中利用定时器制作动画 - [MATLAB]. 84

42、MATLAB如何从GUI中返回参数 - [MATLAB]. 86

43、MATLAB 中GUI子程序的参数传递 - [MATLAB]. 87

44、Matlab保存axes上的图的问题(包括坐标轴)... 88

45、Matlab鼠标控制的两个GUI例子(附代码)... 91

46、分享初学的一个GUI例子--新手好好看看(图)... 97

47、axes清除畫面... 113

48、GUI中调用自己制作的帮助文件... 114

49、关于从gui调用simulink. 114

50、如何将菜单中退出项和窗口关闭的回调函数合并?... 117

51、matlab 日历程序... 119

52、如何在GUI里得一个axes实现双Y坐标轴... 121

53、如何实现动态的GUI界面... 121

54、关于GUI和simulink参数传递和执行... 122

55、代码运行时间的计时方法... 134

56、如何在GUI指定的axes中再画一个axes. 135

57、按下鼠标左键并拖动鼠标时的作图方法... 136

58、图像处理相关资料... 137

59、保存axes坐标轴上画的曲线或图形... 140

60、在GUI中如何打开IE. 141

61、gui输入数据,通过rs232传给芯片... 141

62、Matlab关于gui和excel的问题... 142

63、matlab 如何显示数学公式... 145

64、修改matlab自带的tabdlg的字体和颜色... 148

65、求助 Matlab的RGB彩色图合成... 148

66、如何删除已绘制的曲线?... 149

67、总结一下,MATLAB中随机矩阵获得... 150

68、【原创】GUI设计中背景音乐的定制与关闭... 153

69、Matlab如何改变GRID 网格线的颜色?... 156

71、把plot图上的某些曲线排除在lengend之外,即不用legend标注出来... 157

72、如何连续对矩阵追加数值... 158

73、两个等直径圆管的交线... 160

74、Matlab的csvread读取数据的问题... 161

75、在对数坐标系插值的问题... 162

76、实现在原有图像上的部分图像变为白色... 162

78、如何实现双击listbox中的条目才表示选中... 163

79、如何删除矩阵中的NaN. 164

80、用平行截面法讨论由曲面z=x^2-y^2构成的马鞍面形状。... 164

81、如何利用ode45解方程... 165

82、Matlab图片如何批处理?pic变量逐一读取文件夹所有图片名... 165

83、方程为:exp(-x)=cos(x),用迭代法求出最小的正根,当相对误差<=10e-6时,求根结束。... 166

84、通过鼠标点击控制循环... 166

85、图像经连续小波分解后的显示效果图... 167

85-1、怎样查看图像的属性... 169

86、想产生如下的矩阵:6行10列,每行都是1 2 3 4 5 6 7 8 9 10。... 169

87、textread读取.txt中数据... 169

88、数制之间的转换怎么实现... 170

89、matlab读取大数据文件的方法... 172

90、从状态空间方程转换为传递函数... 174

91、生成0 1 2 3 4 5 6 7 8 随机出现大小为20X20的矩阵!... 174

92、存储绘图过程,并播放视频... 175

93、如何同时读入多个文件,并作图?... 175

94、MATLAB GUI编程中几个有用的程序段... 177

95、Matlab如何在给定区域随机取点?... 180

96、数据如何导入到workspace中,并执行?在GUI里面,怎么传递处理。... 180

97、matlab下画‘心’的程序。... 181

98、点到直线的距离怎么求?... 181

99、如何绘制正态分布图?... 185

100、matlab作图时,如何只保存图像而不显示图像... 185

101、在三维图中只显示x,y轴,不显示z轴... 186

102、cell array和矩阵的显示... 186

103、矩阵形式的转换... 188

104、如何判断鼠标是否在figure内的某一区域?... 189

105、一个有用的程序... 189

106、窗口的最大化、最小化、图标、置顶... 191

107、连续生成文件名的问题... 193

108、编辑框edit中输入公式后的绘图问题... 194

109、MATLAB中plot命令绘图微调的几个注记 (转自职业仓库)... 195

110、MATlab 三维图中显示z坐标轴的极大极小值... 203

111、如何一次性清空GUI程序的handles结构中的变量... 203

112、Matlab如何给元胞中的每个一维向量前增加同一个数?... 204

113、用guide生成的不同GUI之间控件的互相操作... 206

114、自定义Matlab figure 工具栏按钮... 208

115、matlab 有没有按某个小数位数做四舍五入的函数?... 209

116、有关矩阵中小于某值的数取整的问题... 209

117、Matlab表面被截后的部分... 210

118、如何是imshow显示的图像充满整个figure?... 211

119、图像颜色统计直方图... 211

120、Matlab如何将大元胞数组写入到txt文件... 212

121、构造特殊矩阵(右螺线状的)... 213

122、figure中多坐标轴中曲线的legend标注... 214

123、GUI中鼠标选中并显示曲线的类型及坐标... 215

124、Matlab中y=1\x围绕y轴旋转形成的旋转曲面... 218

125、GUI程序一开始以‘最大化’显示的问题... 219

126、如何实现文本自动转换... 219

1、GUI新手之——教你读懂GUI的M文件

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函数。所以你只用管把代码写入响应的函数名下就行了。至于系统为什么会自动调用,我们不用管,我们只用知道,我点击鼠标,我拖动滑竿时,系统会执行哪里的代码。就够了。

一、 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

二、 M-File 里的各个函数代表什么意思

在设计面板设计排列好自己需要的各种按钮或者编辑框之后,下一步任务便是添加自己的响应代码。

Opening function  添加在它名下的代码,在GUI开始运行但是还不可见的时候执行。这里的代码一般都是做一些初始化工作的。

Output function  如果有需要,可以向命令行输出数据。(这个函数我没用过,不多说了^_^)

Callbacks   每一次点击按钮或者向输入框输入数据或者拖动滑竿,这些控件名下的callback就会执行一次。

函数的输入参数
M-File名下的全部function都会有这两个输入参数
hObject  它代表的是当前的这个控件(也就是你点哪一个按钮或者拖的哪一个滑竿)
handles  它代表的是现在这整一个GUI界面
对这两个变量进行修改后
guidata(hObject, handles);   进行保存,否则修改无效;P

三、 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传入数据的目的。

四、 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合用。

五、 Callbacks 回调函数
当你对组件做点击或者别的动作,则自动调用相应的callback。callback的名字取决于你的控件的tag和控件类型以及响应类型。
function print_button_Callback(hObject, eventdata, handles)

2、GUI程序中改变current directory引起的问题

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.

3、GUI中h0bject和handles 的区别

刚学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内的不同控件的回调函数内传递数据。

4、handles结构中句柄和对象的关联问题

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结构。

5、Matlab利用定时器连续显示图片的问题

利用定时器连续显示图片,里面用的是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 时,就会把波形绘制到指定坐标轴中。

5-1、GUI中实现在图片任意位置上标注text

利用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.

5-2、使用edit的另外一种callback

如果edit是多行的。想点击每一行的时候,能执行不同的事件,那么可以使用:

代码:
contents=get(hObject,'String');
a=contents(get(hObject,'Value'))

那么a就是你选择的对应的那一行。

6、MATLAB 如何实现图像的任意裁减?

1 使用 imrect imcrop 函数相结合 就可以实现截图功能。

用imcrop函数,例如:

I = imread('circuit.tif');

I2 = imcrop(I,[60 40 100 90]);

figure, imshow(I)

figure, imshow(I2)

见自己编写的程序:picturecrop。

2 )剪取图像的中间区域: 我想裁剪图像中间的部分,就是去掉图像周围部分!

1、首先取得图像的显示范围:
x1=get(gca,'xlim');
y1=get(gca,'ylim');
width=x1(1,2)-x1(1,1);
height=y1(1,2)-y1(1,1);
2、求的图像中心的坐标:
x0=x1(1,1)+width/2;
y0=y1(1,1)+height/2;
3、如果想剪切图像显示区域的1/4(以图像中心向四周剪切),则:
a=width/4;
b=height/4;
4、计算裁剪区域:(以图像中心点为裁剪中心)
rect=[x0-a/2 y0-b/2 a b]
5、用imcrop裁剪:
a=imcrop(A,rect);

7、坐标轴标注刻度、网格、文字方向

用两个矩阵画了一个图像,用grid on添加了网格,但是默认的网格太稀了,想要密一点的,该怎么解决?

1 用 set(AX,'XMinorGrid','on');set(AX,'XMinorGrid','on');

2、(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]);

8、Matlab中对uitable的操作:调节各列宽度,设定某列是可编辑的

解决办法:

例子:例如想建立三行三列的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);
显示结果如下:

其中,第三列的数值是可以编辑的。

9、将在Matlab下编写的GUI转成独立于Matlab平台的应用程序

将在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

10、要将用Matlab语言编写的函数文件编译成可独立执行的*.exe文件

要将用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生成独立可执行的程序

一、生成独立可执行的程序(exe文件)步骤

1、安装编译器。可有多种选择,本机安装的是microsoft visual c++ 6.0;

2、设置编译器。在matlab命令行输入mbuild -setup,选择安装的c编译器;

3、调用编译器。输入mcc -m filaname,filaname为要转成exe的m文件;

在以前的版本中,用编译命令mcc -B sglcpp filaname;自2006的版本后,替换为mcc -m filaname;

4、安装MATLAB7\toolbox\compiler\deploy\win32目录下的MCRInstaller。

二、脱离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,同时将可执行文件的图标放在桌面。

11、matlab GUI程序转换成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不支持符号工具箱的编译。只好避开使用此函数。

12、gui生成独立的应用程序的发布问题

“将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:用户系统路径的添加是在环境变量里,我的电脑——>属性——>高级——>环境变量,添加即可。

13、GUI控制simulink模块及参数的综合实例!

最近在论坛上学习,虽然进度很慢,但收获不少!
现在将我在学习过程中对于GUI控制simulink时遇到过困难的一些功能做成一个综合实例放在这里,打个包希望给大家省点钱,也希望能够帮助到论坛里需要的朋友!同时以此感谢在我学习的过程中热心帮助过我的朋友们,感谢论坛! GUI and Simulink.rar (14.88 KB)

该实例主要功能:
1、演示了GUI界面的布局和效果;
2、演示了togglebutton、pushbutton对simulink模块参数的设置方法;
3、演示了Edit text 和slider的联合使用,及利用edit text 和slider 对simulink 参数的动态修改;
4、演示了simulink参数在GUI上的显示和更显;
5、语句进行了注释,为便于编译没用中文,大家凑或者看吧!

管理员:“会员RayneZ提醒:该帖子的楼主贴了一个GUI+Simulink的示例文件,但是有些小错误,matlab在运行的时候提示出错。
检查了一下,错误原因在GUI_ex11.mdl这个文件中的fcn2模块中的函数编写有些问题
第四行和第六行的逻辑判断语句中的&应该改为&&
更改后程序可以正常运行。

13-1、在axes显示图像后,在图像上单击鼠标时,回调函数的定义规则和使用方法

想在一个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 的参数传递方法有:

(另外有用的代码)

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;

14、如何在循环中加入waitbar,并在waitbar上添加‘取消’按钮

有一个循环用来采集数据的,想加入一个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;

% do stuff

效果如下:

另: 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,符合自己的要求就可以了。

15、在matlab中对信号进行FFT变换

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)

16、动态显示figure中曲线的x-y坐标值的一个函数

函数定义如下所示。

使用方法为:

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;

if ~isstr(arg)

handle = arg;

arg = 'init';

switch arg

case 'init'

if ~ishandle(handle)

error('h is not a handle')

[h,ax] = h2hax(handle);

% delete old dynamic text object

ht = findobj(h,'tag',[mfilename '_text']);

if any(ht)

delete(ht)

% 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');

p = get(ax,'currentpoint');

set(ht,'string',sprintf('%g %g', p(1),p(3)));

case 'delete'

if ~exist('h','var')

h = gcf;

[h,ax] = h2hax(h);

set(h,'windowbuttonmotionfcn','')

ht = findobj(h,'tag',[mfilename '_text']);

delete(ht)

% ----------

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');

=========================================================

17、在GUI界面的打开按钮中,如何对文件进行操作

我要的数据是保存在一组具有相同前缀名*.dat,*.atr,*.hea中的。只有3个同时被使用,数据才能起作用。

我想做一个的界面,一个最基本的功能就是“打开”按钮,它的作用是打开*.dat文件,并匹配和*.dat具有相同文件名的另外两个文件:*.atr,*.hea。实际上就是我表面上只是打开了那个*.dat文件,但程序会搜索和*.dat具有相同文件名的另外两个文件:*.atr,*.hea,一起打开,并把它们保存在3个变量里。

现在的困难是如何在同一个文件夹里搜索到另外两个文件?

解决方法:

1、给你个例子:
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、 %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]);
这样就可以了,剩下的你自己写

18、Matlab不同控件之间的数据传递问题

本人做了一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];

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];

A=[a b c d];

当不按按钮5时,d为空矩阵,则输出前三个矩阵;当按了按钮5时,d被赋值,不为空,则输出a,b,c,d四个矩阵。

19、在edit box里输入相关数据后,直接按回车键,不用鼠标点击pushbutton 就可以直接执行

请教:让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)种方法是可行的。以上方法经实际测试,均是可行的!

19-1 GUI使用editbox输入数据后如何自动清除数据

我编了一个GUI, 使用的时候会需要输入一些数据, 我放了一个editbox和一个按钮"Enter", 用的时候就是在editbox里面输入数据, 然后按"Enter"确认. 现在问题就是输入好数据,按了Enter之后, editbox里面的数据还在, 下次再输入的时候就要先删除后再输入, 我想问一下有没有什么办法能够让按了Enter键之后, editbox里面的数据就会清除掉, 这样下次再输入的时候就不用先删除了。

在enter按钮的回调函数里加入如下代码处理即可:
value1=get(handles.edit1,'string');%先取得编辑框的数据
set(handles.edit1,'string','');%再把编辑框清空

20、在GUI中,计算结果怎么用excel来保存到指定的文件夹中

问题:GUI设计的结果怎么用EXCEL来保存到指定的文件夹。

说明:根据论坛上的例子做了个GUI界面,结果可以保存到EXCEL里面,但保存的路径只能是在当前文件夹,我希望保存到指定的文件夹,怎样才能把数据结果以EXCEL表格的形式保存到指定的文件夹?高手指点一下,不胜感激。。。

解决方法:

例如:要把‘第一行’、‘第二行’、‘第三行’分别添加到 excel 表格的三列可开头,用以下命令:

M={‘ 第一行 ’,’ 第二行 ’,’ 第三行 ’}; % 定义为 cell 类型

xlswrite(‘myexcel.xls’,M);

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');

21、如何得到popupmenu选项中最后一个字符串的VALUE值

在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)  %最后一行所处行数

22、回调函数互相调用的问题

想在一个按钮的回调函数下运行另一个回调函数,句子该如何写?

就像如下调用就可以。回调函数没有什么特别的,也是普通的函数,只不过它是响应控件的操作的。

解决方法:

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

22-2string和number相互转换的问题

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转换为数字类型后才能使用。

23、这样的功能的pushbutton的callback怎么写呀,谢谢了

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('编辑框为空!')

% 运行下面的代码

解决方法:

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('编辑框为空!')

% 运行下面的代码

case 'string2'

24、GUI中axes使用subplot时的清空及axes大小的固定的解决方法

看到过好几个类似下面问题的帖子:
1、axes显示图片时随着图片的大小变化,如何固定axes显示图片大小;
2、当在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

25、退出GUI时如何把全局变量中的值清空?

我定义了一个global img=imread('x.bmp');一些处理img的程序。但是我退出界面程序时 再进入程序时img还是最后处理后的图像,怎么在退出程序时把img清空呢?

clear all;

26、从串口接受数据时,如何把波形绘制到指定的坐标轴上?

在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。就可以了。否则,在定时器或串口的回调函数里绘图都会出现这种情况。

27、两个GUI之间如何传递数据

想做一个两个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的值。

4、 可以通过 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中的变量

28-1 几个有用的帖子

引自王辉版主回复的一个帖子: http://www.ilovematlab.cn/thread-56517-1-3.html
===========================================================
你看看这些帖子:
题目:(不同 GUI 之间控件的调用(原创))
论坛讨论地址:
http://www.ilovematlab.cn/thread-52762-1-1.html
功能描述:
1、利用handles结构在控件之间传递数据。利用guihandles获得与传入的句柄相关联的handles结构,从而对不同GUI的控件进行操作。
2、 有两个GUI: GUI1和GUI2,在GUI1中可以操作GUI2的坐标轴,绘制曲线;同样,在GUI2中可以操作GUI1的坐标轴,绘制曲线。
3、在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
实现功能描述:
1、利用handles结构在控件之间传递数据。利用guihandles获得与传入的句柄相关联的handles结构,从而对不同GUI的控件进行操作。
2、 有两个GUI: GUI1和GUI2,在GUI1中可以操作GUI2的坐标轴,绘制曲线;同样,在GUI2中可以操作GUI1的坐标轴,绘制曲线。
3、在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内、外)和优劣。

28-2、GUI之间互相调用和关闭问题

假设有两个GUI:GUI1和GUI2,它们之间怎么互相调用和关闭?

解决方法:

假设在GUI1的按钮的回调函数里调用GUI2:

hGUI2=GUI2(); % hGUI2是GUI2对象的句柄

若想在GUI1中关闭GUI2,只需要代码:

close(hGUI2);

29、GUI timer定时器

这是显示时间的一段定时器代码,注释是我自己写的,希望大牛帮小弟看看。

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'));

30、如何在循环中加入waitbar

有一个循环用来采集数据的,想加入一个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

31、如何连续读入图片!!

如何一次性读入多张图片,并且让它们逐个处理比如像我上个问题所说的图像分割,就是只按一下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里就可以,修改里面的路径。

32、如何把此次输入的值保存为下一次初始化的值

想实现这样的操作:此次输入数据,通过保存按钮作为下一次打开时的初始化的数据。

解决方法:

这个是读写文件的问题,你可以把数据保存在文件里,然后每次打开GUI的时候,就读这些文件。每次退出时,保存当前数据,覆盖原来的文件。

33、Matlab关于解决自动保存gcf的问题

具体问题:使用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 exe d system
rgb = ind2rgb(im,map);   %Convert image data
end
str = sprintf('%drect.png', rectn);
imwrite(rgb, str);

34-1、在matlab里面如何读取excel里面的数据或者写入数据

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);

35、Matlab GUI不同控件之间的数据传递问题

本人做了一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四个矩阵。

36、怎么统计一个十进制数中"0"的个数??求助!

题目:编写M函数统计十进制数值中"0"的个数,然后编写脚本文件实现统计所有自然数1~2006中"0"的总个数。

a=102030405;
b=num2str(a);
c=findstr('0',b);
n=length(c);

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);

37、Matlab对listbox里的条目能否一条条单独设置回调函数?

如果不能,那么想要达到这种效果应该怎么办?

问题说明:

在我设计的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)
当我分别点击“Image1、Image2、...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.

38、键盘操作:matlab GUI中如何取得从键盘输入的按键的键值

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('你按下了空格键!!!!');

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

40、matlab 截图、图像处理

要求利用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);

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

else h=1;

result(i,j)=h*g(i,j);

result=ifftshift(result);

y2=ifft2(result);

y3=uint8(real(y2));

imshow(y3);                               % 显示滤波处理后的图像

imwrite(y3,'gaussiangao.jpg');

title('高斯高通滤波')

41、MATLAB GUI中利用定时器制作动画 - [ MATLAB ]

版权声明 :转载时请以超链接形式标明文章原始出处和作者信息及 本声明
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});

42、MATLAB如何从GUI中返回参数 - [ MATLAB ]

版权声明 :转载时请以超链接形式标明文章原始出处和作者信息及 本声明
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的返回值被传错了地方。

43、MATLAB 中GUI子程序的参数传递 - [ MATLAB ]

版权声明 :转载时请以超链接形式标明文章原始出处和作者信息及 本声明
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的返回值被传错了地方。

44、Matlab保存axes上的图的问题(包括坐标轴)

做了一个按钮“保存”,可以另存为画在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 GUI DATA)
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);

这样就可以了,谢了!

45、Matlab鼠标控制的两个GUI例子(附代码)

相信大家都知道,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

步骤是需要利用GUIDE添加一个Static和一个 Text Axes,然后添加Callback函数即可,即可实现如下的画笔功能。

46、分享初学的一个GUI例子--新手好好看看(图)


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

47、axes清除畫面

清除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',[])

48、GUI中调用自己制作的帮助文件

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);

49、关于从gui调用simulink

我这里有一个例子,不知道能不能帮上你,我是在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)

50、如何将菜单中退出项和窗口关闭的回调函数合并?

菜单中退出项的回调函数可以如下:

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 GUI DATA)
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});

51、matlab 日历程序

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');

ss='b';

qq=eomday(y,m);

for k=1:qq;

n=datenum(y,m,k);

[da,w] = weekday(n);

if k==d;

ss='r';

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;

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);

while 1

set(Tq,'String',datestr(now,13));

pause(1);

52、如何在GUI里得一个axes实现双Y坐标轴

这个叫做“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');

53、如何实现动态的GUI界面

开发动态GUI是一件比较有挑战性的工作。

首先说明一下,什么是动态GUI: 就是说你的程序, 根据用户选择的不同,要产生相应的GUI, 举个简单例子,用户选了3x3,那么你的gui界面上,就要出现3x3的编辑框。

比如说,上传我在开发“Matlab实现层次分析法”的时候(如下图),用的是GUIDE开发的,没有直接单靠写代码(人比较懒),一开始开发的时候,比较容易。后来牵涉到动态的时候,就很麻烦,因为用户很有可能选择一个10x10的编辑框, 那么,如果手动开发一个10*10的编辑框,是一件多么痛苦的事情啊(本科时候,我这样做过,当时做sliding mode control, 需要输入很多参数,根据用户的需要,然后决定让某些编辑框显示或者隐藏,这个Matlab实现层次分析法也是,这样不好), 所以了, 我建议大家,遇到这样的情况,需要开发动态的GUI, 用代码来帮你生成GUI
如果你对写动态gui有什么心得,或者什么经验,我们不妨讨论一下,看看什么样的代码或者方法,可以生成最适合用户需要的动态GUI.欢迎跟帖讨论。

见实例程序: dynamicgui.m

54、关于GUI和simulink参数传递和执行

利用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)

55、代码运行时间的计时方法

代码运行时间的计时方法:
1、整段程序代码的计时:
tic 。。。。
toc   表示计算tic和tc之间的时间
这种方法只能计算出大体的时间
2、etime(t1,t2)来计算t1,t2之间的时间差,应用的形式:
t0=clock
程序段
etime(clock,t0)
3、也可以用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]

56、如何在GUI指定的axes中再画一个axes

具体情况如下:
我采集了一幅图像有两个光斑,在我的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)');

57、按下鼠标左键并拖动鼠标时的作图方法

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)

58、图像处理相关资料

各位大虾,我接触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

59、保存axes坐标轴上画的曲线或图形

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]);

60、在GUI中如何打开IE

在GUI中按了某个按钮之后,想用IE打开网页,由于页面中有javascript脚本,所以用MATLAB自带的浏览器不能运行那位朋友知道怎样打开IE并添加想要的地址 或者改变Matlab自带的浏览器为IE。

解决办法:

web -browser  www.ilovematlab.cn

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

61、gui输入数据,通过rs232传给芯片

因为刚刚接触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)

62、Matlab关于gui和excel的问题

我想点一下按钮存一个数在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等。

63、matlab 如何显示数学公式

调试下面的例子:

%% 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/.

64、修改matlab自带的tabdlg的字体和颜色

修改第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');

就可以修改标签页的字体颜色和大小了。

65、求助 Matlab的RGB彩色图合成

我把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);

66、如何删除已绘制的曲线?

有两条曲线,分别为数据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');
这时,第二条曲线就删除了。

67、总结一下,MATLAB中随机矩阵获得

这几天在论坛里又收获不少,总结了一些关于得到随机矩阵的函数,希望对大家有所帮助。
欢迎回帖给与补充,呵呵,谢谢先。
一、randperm
randperm(n);
产生从零到n长度为n的随机整数
例如

>> randperm(10)
ans =
8     2    10     7     4     3     6     9     5     1
>>

二、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

三、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

四、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

五、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

不当之处,望大家不吝指教。

68、【原创】GUI设计中背景音乐的定制与关闭

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属性,可以实现循环播放。

69、Matlab如何改变GRID 网格线的颜色?

如题,想在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');

71、把plot图上的某些曲线排除在lengend之外,即不用legend标注出来

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’时,表示排除在外。

72、如何连续对矩阵追加数值

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);

73、两个等直径圆管的交线

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

74、Matlab的csvread读取数据的问题

u0=csvread('data.csv')不好用,因为我的文件第一行是文本,好像csvread要求所读取的csv文件必须都是数据。什么语句能删除csv文件里面的第一行,然后读取单元格A3到A10的数据?(假设csv里面有20*20的数据)

用如下方式读取:
csvread('D:\chengji.txt',1,0); %把第一行的内容排除

代码: txt文件的内容

liu1,liu2,liu3
80,75,65
60,65,35

代码:
>> csvread('D:\chengji.txt',1,0)
ans =
80    75    65
60    65    35

75、在对数坐标系插值的问题

我在双对数坐标系(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');

76、实现在原有图像上的部分图像变为白色

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.

运行结果:

78、如何实现双击listbox中的条目才表示选中

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});

79、如何删除矩阵中的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,:)=[]

80 、用平行截面法讨论由曲面 z=x^2-y^2 构成的马鞍面形状。

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;

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);

81、如何利用ode45解方程

function myname()

global m c k

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))];

82、Matlab图片如何批处理?pic变量逐一读取文件夹所有图片名

有一个文件夹,里面有一些图片(比如'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

83、方程为:exp(-x)=cos(x),用迭代法求出最小的正根,当相对误差<=10e-6时,求根结束。

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 方程根 ');

84、通过鼠标点击控制循环

我在M文件里写了一个while循环,运行GUI以后,在GUI范围内,鼠标任意点击某处,循环运行一次得到结果,即通过鼠标点击,手动控制一次一次循环知道结束。

1、定义全局变量:global begin; 用来控制循环。定义 global num; 来控制循环次数,初始值为num=1
2、在windowbuttondownFcn函数中加入while循环。
3、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;

85、图像经连续小波分解后的显示效果图

% 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

85-1、怎样查看图像的属性

例如,图像放在D盘内,名字是brand.jpeg。则命令:

info = imfinfo('brand.jpeg');

用来查看图像的属性:

86、想产生如下的矩阵:6行10列,每行都是1 2 3 4 5 6 7 8 9 10。

方法如下:

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

87、textread读取.txt中数据

要同时读取这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']);

x=1:k;

plot(x,y,'marker','.','markersize',12);

for ii=1:k

line([x(ii) x(ii)],[y(ii) 0]);

88、数制之间的转换怎么实现

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';

while n~=0

p(k)=rem(n,b);

n=fix(n/b);

k=k+1;

k=k-1;

strdec='';

while k>=1

kb=p(k);

strdec=strcat(strdec,ch1(kb+1:kb+1));

k=k-1;

dec=strdec;

set(ht,'string',num2str(dec));

function myclose(hobj,event)

close(hf);

89、matlab读取大数据文件的方法

function[t datafile]=readtxt1(filename)
fprintf(' 开始读取 数据 ,请等待! \n');
main_path = 'C:\ MATLAB 7\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

90、从状态空间方程转换为传递函数

% 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)

91、生成0 1 2 3 4 5 6 7 8 随机出现大小为20X20的矩阵!

1、方法1:

clc;
clear;
x=randperm(400);
x=mod(x,9);
reshape(x,20,20)

2、方法2:randint(20,20,[0 8])

92、存储绘图过程,并播放视频

for j = 1:100

x=1:j;

y=sin(x);

plot(x,y);

F(j) = getframe;

pause(1);

movie(F,100);% 播放视频200次

93、如何同时读入多个文件,并作图?

用下面的方法:把你的文件名放在红色字体标注的语句里,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

94、MATLAB GUI编程中几个有用的程序段

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

% 添加当前路径下的所有子目录

addpath(genpath(pwd));

addpath(genpath(currPath));

2 GUI 中使用 Axes 控件

% 1.删除所有画线及对应图例

% 查找Axes控件中的画线

sameLines = findobj('type','line');

% 逐一删除这些画线

for i = 1 :length(sameLines)

delete(sameLines(i))

% 获取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);

% 获取原有的图例

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', '仿真结果报告');

95、Matlab如何在给定区域随机取点?

例如,给定区域[x y width height],则随机取点的程序为:
x = x + width * rand(1);
y=y+height*rand(1);

96、数据如何导入到workspace中,并执行?在GUI里面,怎么传递处理。

我刚刚上手学习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');

97、matlab下画‘心’的程序。

t=linspace(0,2*pi,1000);

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

98、点到直线的距离怎么求?

已知点的坐标a=[0.3536,1.1036];组成线段的两个点的坐标分别为b=[0.7071,0.5],c=[0,1]
该如何求出点a到线段bc的垂直距离?

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

方法二、解方程

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);

方法四、三维空间中点的坐标

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

99、如何绘制正态分布图?

ezplot('25*exp(-(((x-50)/0.2)^2))',[1 100]);
set(gca,'xlim',[30 70]);

100、matlab作图时,如何只保存图像而不显示图像

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');

101、在三维图中只显示x,y轴,不显示z轴

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]);

102、cell array和矩阵的显示

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

2     3

4     5

6     7

[1]    [1x2 double]

[1]    [1x2 double]    [2x2 double]

ans =

ans =

2     3

ans =

4     5

6     7

103、矩阵形式的转换

比如有一个矩阵
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

104、如何判断鼠标是否在figure内的某一区域?

首先,设置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)));

105、一个有用的程序

G=tf(2.25,[2756.25,105,1],'inputdelay',5);

h=figure(1);

axes();

step(G);

title('¿ª»·½×Ô¾ÏìÓ¦ÇúÏß');

xlabel('time');

ylabel('step response');

K=2.25;T=50,tao=105;

num=2.25;

den=[2756.25 105 1];

G=tf(num,den);

s=tf('s');

PKp=T/(K*tao);

Gk1=PKp*G;

sys1=feedback(Gk1,1,-1);

figure(2);

axes();

step(sys1);

title('P¿ØÖƽ×Ô¾ÏìÓ¦ÇúÏß');

xlabel('time');

ylabel('step response');

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

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');

106、窗口的最大化、最小化、图标、置顶

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中似乎并不好用。

107、连续生成文件名的问题

filename={};
for i=1:50
fname=strcat('image',num2str(i),'.mat');
filename=[filename;cellstr(fname)];
end

108、编辑框edit中输入公式后的绘图问题

在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);

109、MATLAB中plot命令绘图微调的几个注记 (转自职业仓库)

绘前篇用“Grads平均值输出到硬盘”日志,这里就是用MATLAB来绘折线图。平时用MATLAB不多,因此编写编看帮助文档,整理了一些有用的注记写在这里备忘,也供朋友借鉴。这段M文件注记几点:

1、    MATLAB如何从硬盘读取文件。

2、    如何微调subplot子图的位置。

3、    plot命令绘曲线时,曲线上的标志如何调整大小。

4、    坐标轴的调整。

5、    box on命令

6、    坐标标题中如何标上标。

7、    如何调整图示(legend)的位置。

8、    以上内容在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)' );单位里有上标,^表示后续一个字符为上标。

下述代码绘子图2、3、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相对子图的位置还要随画图窗口大小变化而变化。如果你看不懂这句,试试就知道了。

110、MATlab 三维图中显示z坐标轴的极大极小值

画了一个三维图,想在这个图上用一个竖着的条 两端表示出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})

111、如何一次性清空GUI程序的handles结构中的变量

在处理第一个文件时,产生了
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结构上的变量都一次性清除了。

112、Matlab如何给元胞中的每个一维向量前增加同一个数?

如何给元胞中的多个一维向量前增加同一个数?比如:

原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

113、用guide生成的不同GUI之间控件的互相操作

利用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的值,两个界面是同时打开着的。

1、 这个问题是主 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设定其数值

2、 如何实现在从 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之间共享数据的方法。

114、自定义Matlab figure 工具栏按钮

若将 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

只要给定匹配按钮 tag 名称的正则表达式,就可以选择我们想要的按钮,例如:

KeepToolbarButton(handles.figure1, '(zoomout)|(zoomin)|(pan)');

115、matlab 有没有按某个小数位数做四舍五入的函数?

>> a = 3.2435;

>> digits(2)

>> vpa(a)

ans =

>> digits(3)

>> vpa(a)

ans =

116、有关矩阵中小于某值的数取整的问题

a(find(a(:)<eps))=floor(a(find(a(:)<eps)));

用一条语句就可以把a矩阵中小于eps的数值取为0了。

117、Matlab表面被截后的部分

请教一下,如何用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]);

118、如何是imshow显示的图像充满整个figure?

logo1 = '5.jpg';

figure;

imshow(logo1,'Border','tight')

119、图像颜色统计直方图

ii=imread('5.jpg');%5.jpg是256x256的灰度图,gray image

x=1:256;

figure;

hist(ii,x);

120、Matlab如何将大元胞数组写入到txt文件

例如R是个24X23的cell结构的矩阵,把其写入到myfile.txt中:

1、数据写入:
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不存在,则自动创建
2、数据读取:
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类型的矩阵

121、构造特殊矩阵(右螺线状的)

clc;clear;

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;

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;

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

122、figure中多坐标轴中曲线的legend标注

把要标注的曲线的句柄和字符串包含到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);

123、GUI中鼠标选中并显示曲线的类型及坐标

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');

legend('off'); %否则,关闭legend

124、Matlab中y=1\x围绕y轴旋转形成的旋转曲面

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

125、GUI程序一开始以‘最大化’显示的问题

在Outputfcn函数的最后添加如下语句:

javaFrame = get(gcf,'JavaFrame');

set(javaFrame,'Maximized',1)

就可以实现GUI窗口一开始便以‘最大化’的形式显示。

126、如何实现文本自动转换

假定在文本框中输入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;

for ii=1:3

if strcmp(text{ii,1},string_edit)

strout=text{ii,2};

if ~isempty(strout)

set(handles.edit1,'string',strout);