首页 > Matlab > Matlab/GUI笔记

Matlab/GUI笔记

2013年7月5日 发表评论 阅读评论

不显示坐标刻度:

set(gca,’xtick’,[])

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

频率响应:
[H,F]=freqz(b,1,512);

plot(F,20*log10(abs(H))); 

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

滤波:

Y = Filter(A,B,X);

A/B虑X得到Y
=================================================
播放音乐:

sound(x,fs) 

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

摄像头模块:

% 获取摄像头信息(imaqhwinfo)
imaqInfo = imaqhwinfo;
winvideoinfo = imaqhwinfo(‘winvideo’);
n=length(winvideoinfo.DeviceInfo);% 看系统中有几个摄像头

% 调参数,设置成使用最后一个摄像头
CamNum=n;
device = winvideoinfo.DeviceInfo(CamNum)

% 分辨率设置,发现320×240时合适,640×480时只能预览(若要处理则会表现出较大的延时)
Format=device.SupportedFormats(3);% ‘YUY2_320x240’
%Format=device.SupportedFormats(1);% ‘YUY2_160x120’
% Format=device.SupportedFormats(end); % ‘YUY2_640x480’
Format=char(Format);% 转换成字符串

% 申请内存空间
imaqmem(30000000);

VID = videoinput(‘winvideo’,CamNum,Format);% 创建视频输入对象(videoinput)
preview(VID); % 显示原始视频

start(VID);

h=figure(‘NumberTitle’,’off’,’Name’,’处理后的视频’,’MenuBar’,’none’, ‘Visible’, ‘on’); set(h,’doublebuffer’,’on’);

while ishandle(h) % 判断是否有效的图像对象句柄
Iyuv=getsnapshot (VID); % 捕获1帧图像
I=ycbcr2rgb(Iyuv); % 将图像从YUV空间转换成RGB空间
flushdata(VID); % 清除数据获取引擎的所有数据、置属性SamplesAvailable为0
%TODO%
%%
drawnow; % 实时更新图像,这句话很重要
end

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

计算运行时间:

tic;

%%%%TODO%%%%

%%%%%%%%%%%%

time_use = toc;

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

画图不同颜色连线:

h=plot(x(ii),y(ii),’o’);
hold on;
col=rand(1,3);
set(h,’Color’,col,’MarkerFaceColor’,col);
xi1=x(i)*ones(size(ii));
xi2=y(i)*ones(size(ii));
line([x(ii)’,xi1]’,[y(ii)’,xi2]’,’Color’,col);

=================================================
图像中书写文字:

text(.5,.5,[‘$’,latex(x^2),’$’],’interpreter’,’latex’,’HorizontalAlignment’,’center’,’fontsize’,18)

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

读取wav文件:

[x, Fs, Bits]=wavread('readtest.wav'); 
if Bits==16 
    x=x*32768; 
elseif Bits==8 
    x=x*128; 
end

播放wav文件:

music(x)

保存wav文件:

wavwrite(zz’,44100,16,num2str(hm));

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

zplane:

num = input(‘Type in the numerator coefficients = ‘);
den = input(‘Type in the denominator coefficients = ‘);
K = num(1)/den(1);
Numfactors = factorize(num);%分解质因数
Denfactors = factorize(den);
disp(‘Numerator factors’);disp(Numfactors);
disp(‘Denominator factors’);disp(Denfactors);
disp(‘Gain constant’);disp(K);
zplane(num,den)

输出:

Numerator factors

1.000000000000000   -2.100000000000001    5.000000000000003

1.000000000000000   -0.399999999999998    0.900000000000000 

Denominator factors

1.000000000000000    2.000000000000000    4.999999999999996

1.000000000000000   -0.200000000000000    0.400000000000004 

Gain constant

0.500000000000000

所以原始等于:

0.5*(1-2.1 z-1 +5 z-2 )(1-0.4 z-1 + 0.9 z-2  )/(1+2 z-1 + 5 z-2 )/(1 – 0.2 z-1 + 0.5 z-2)

=================================================
转灰度图:

rgb2gray 

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

批量重命名:

file = dir([‘E:english gesture*.txt’]);
for i = 1 : length(file)
str = [‘rename ‘ ‘E:english” “‘ file(i).name ‘.txt’ ‘ ‘ file(i).name(1) num2str(i+1) ‘.txt’];
system(str);
end

dir中文件路径有空格可以直接写,str中用有空格要用” “来代替。

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

数据按指定格式写到一个文本文件中去:

fid=fopen(‘e:/coe_8_v_rotate.arff’,’wt’);%写入文件路径

fprintf(fid,’XXXXXnn’);

fprintf(fid,’%g,’,data);

fclose(fid);

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

1~n的随机排列:

randperm(n)

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

计算众数:

mode

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

随机整数:

out = randint(1,1,[0,100]) 

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

组合数:

nchoosek(5,2)

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

组合结果:

combntns([1 2 3 4],2)

ans =

 1 2
 1 3
 1 4
 2 3
 2 4
 3 4

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

误差累积函数和反运算:

normcdf

norminv

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

符合正态随机分布的随机数:

R = normrnd(MU,SIGMA)

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

绘制双纵坐标系曲线:

plotyy(X1,Y1,X2,Y2)

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

采样:

downsample(a,R)

decimate可以设置滤波器,细节不好控制

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

画时频图:

spectrogram (S, 窗大小, 窗重叠部分大小, 福利叶变换长度,采样率) ) 

或者:

[y,f,t,p] = spectrogram (data, N_w, N_overlap, N_fft, Fs_d,’yaxis’);
surf(t,f,10*log10(abs(p)),’EdgeColor’,’none’);
axis xy; axis tight; colormap(jet); view(0,90);
xlabel(‘Time’);
ylabel(‘Frequency (Hz)’);
colorbar;
=================================================
figure设置全屏:

set(gcf,’outerposition’,get(0,’screensize’)); 
=================================================
按特定格式读取文件的数据:

[a b c d…] = textread(file_name,format);
=================================================
按行读取文件的数据:

fidin=fopen('test.txt'); 
while ~feof(fidin) 
 line_read=fgetl(fidin); 
end 
close(fidin);

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

设置画图data cursor的显示模式:

重写函数myupdatefcn

function doc_datacursormode()

fig = figure;
a = -16; t = 0:60;
plot(t,sin(a*t))
dcm_obj = datacursormode(fig);
set(dcm_obj,’UpdateFcn’,@myupdatefcn)

% Click on line to select data point

function txt = myupdatefcn(empt,event_obj)
pos = get(event_obj,’Position’);
txt = {[‘Time: ‘,num2str(pos(1))],…
[‘Amplitude: ‘,num2str(pos(2))]};

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

指定小数位数格式化字符串:

str=sprintf(‘x=%.3f,y=%.3f’,x,y);
disp(str);

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

plot中添加描述文字:

text(x,y,str,’FontSize’,18);
=================================================

数据拟合工具:

打开cftool
=================================================

图像处理操作:

I=rgb2gray(RGB);%灰度化
imhist(I); %画出直方图对比
newA = histeq(rgb2gray(A));%%直方图均衡化
newA = imresize(newA,[sizeM,sizeN]);

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

排版整理快捷键:

ctrl+i
=================================================

发邮件接口(可以用于程序跑完给自己发一封邮件):

function send_E_mail(from_address, password, to_address, subject, message)

setpref(‘Internet’, ‘E_mail’, from_address);
setpref(‘Internet’, ‘SMTP_Username’, from_address);
setpref(‘Internet’, ‘SMTP_Password’, password);

props = java.lang.System.getProperties;
props.setProperty(‘mail.smtp.auth’,’true’);
props.setProperty(‘mail.smtp.socketFactory.class’,’javax.net.ssl.SSLSocketFactory’);
props.setProperty(‘mail.smtp.socketFactory.port’,’465′);

sendmail(to_address, subject, message);

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

matlab说话:

sp=actxserver(‘SAPI.SpVoice’);
sp.Speak(‘你是猪’)

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

函数绘图:
1)ezplot(‘sin(x)’)
系列函数:ezcontour,ezcontourf,ezmesh,ezmeshc,ezplot3,ezpolar,ezsurf,ezsurfc
2)fplot(‘sin(x)’,[0 2*pi])
3)function y=my_fun(x)
y = sin(x);
调用时:fplot(‘my_fun’,[0 2*pi])
4)匿名函数:
f=@(x)sin(x);%定义x为输入参数
fplot(f,[0 2*pi])
=================================================

双y轴画图:

plotyy()

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

y轴取对数画图:

semilogy ()

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

在鼠标点击的位置显示字符串:

gtext

=================================================
TEX字符:
it斜体,AE设为斜体'{itAE}’
rm正常
text(0,0,’$frac{1}{2}$’,’interpreter’,’latex’)
text(‘string’,’$frac{1}{2}$’,’interpreter’,’latex’,’fontsize’,40,’pos’,[4 1])
=================================================

字符作图:

text(x,y,’D’)
当xy为矩阵的时候,相当于用字符’D’来画图

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

修改text:
text_handle=text(.2,.1,’修改前字符串’);
pause(10);
set(text_handle,’string’,‘修改后字符串’);

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

带背景颜色text:
text(6,1.2,’downarrow aa’,’BackgroundColor’,’b’, ‘FontWeight’,’bold’,’Color’,’y’); 

=================================================
text多行显示:

多行用元胞{‘第一行’,’第二行’}

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

x轴为时间:

datetick

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

各种统计图画法:

面积图:area
柱状图分组画法,bar,输入矩阵每行为一组,bar(x,’group’)
柱状图每组叠加成一列:bar(x,’stack’)
柱状图横着画:barh
阶梯图:stairs
角度直方图rose

=================================================
元胞设置作图多个属性(加上v6)
PN_array={‘Color’,’LineWidth’,’Marker’};
PV_array={‘y’,3,’d’};
plot(‘v6’,cos(x),sin(x),PN_array,PV_array)
或者
PS_array.Color=’m’;PS_array.LineWidth=2;
line(cos(5*x),sin(5*x),PS_array);

=================================================
绘图后不显示菜单栏:
set(gcf,’menubar’,’none’);
恢复
set(gcf,’Menubar’,’figure’);

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

绘图后背景颜色:
set(gcf,’Color’,’w’);
=================================================

绘图窗口大小设置:屏幕左下角为(0,0)
set(gcf,’position’,[50 50 200 200])

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

坐标轴等长:
axis square
=================================================
作图的marker设置:
plot(x,y,’r–s’,’LineWidth’,2,’MarkerEdgeColor’,’k’,’MarkerFaceColor’,’g’,’MarkerSize’,5);
=================================================
多个绘图中设置其中一条的属性:
p=plot(t,y1,t,y2,t,y3,);
set(p(1),’LineWidth’,2);
=================================================
cla:清除坐标轴以外的
clf:清除全部
=================================================
双y轴绘图修改不同y轴属性:
[AX,H1,H2] = plotyy(x,y1,x,y2,’plot’);
set(get(AX(1),’Ylabel’),’String’,’Left Y-axis’)
set(get(AX(2),’Ylabel’),’String’,’Right Y-axis’)
set(H1,’LineStyle’,’–‘)
set(H2,’LineStyle’,’:’)
=================================================
设置坐标刻度记号:
set(gca,’XTick’,-pi:pi/2:pi);
set(gca,’XTickLabel’,{‘-pi’,’-pi/2′,’0′,’pi/2′,’pi’});
set(gca,’fontname’,’symbol’);%用π来代替pi
=================================================
格式化字符串:
sprintf(‘a=%.4f’,1/9)
=================================================
最小刻度网格线:
set(gca,’xminorgrid’,’on’)
=================================================
误差图:
x=linspace(0,2*pi);
y=sin(x);
e = std(y)*ones(size(x));
errorbar(x,y,e,’d’);
=================================================
极坐标转笛卡尔坐标系:
[u,v] = pol2cart(theta,r);
=================================================
羽毛图:(比如用于表示频谱的相位信息)
feather(U,V)
=================================================
箭头图:(极坐标下表示矢量)
compass(x,y)
注:标注text的时候,原点在极坐标原点
=================================================
颜色映射杂七杂八
1)colormap参数可以是hot, hsv, summer, autumn, bone, colorcube, cool, copper, flag, gray, hot, hsv, jet, pink, lines, prism, spring, white, winter 等等
2)自定义映射图:colormap(K)
K是N×3
3)colormapeditor来编辑
4)修改colorbar:
h_CBar = colorbar;
PS=get(h_CBar, ‘Position’);
get(h_CBar,’ylim’)
set(h_CBar,’ytick’,[-6 1 8]);
set(h_CBar,’yticklabel’,{‘上’,’中’,’下’});
5)insert-》colorbar
=================================================
饼状图突出某个值:
x=[20 10 15 25 30];
explode=[0 1 0 0 0];
data={‘a’,’b’,’c’,’d’,’e’};
%获取某部分饼的句柄方式
set(h(4),’FontWeight’,’bold’,’FontSize’,18,’EdgeColor’,’red’);
h=pie(x,explode, data);
=================================================
薄片彩带图:
ribbon(x,y)
=================================================
填充多边形:
fill(x,y,’r’)
=================================================
计算多边形的面积:
ployarea(x,y)
注:不可有交点
=================================================
分散矩阵:
plotmatrix(x,y)
X是P×M,Y是P×N,结果则是N×M
如果plotmatrix(y,y)或plotmatrix(y),对角线为柱状图
=================================================
subplot获取各个子图句柄:
get(gcf,’Children’)
=================================================
坐标轴刻度朝外:
set(gca,’tickdir’,’out’);
=================================================
坐标轴刻度长度:
set(gca,’ticklength’,[0.03 0.025]);
=================================================
指定位置画子图:(左下角为坐标原点)
subplot(‘position’,[0.2,0.05,0.6,0.45]);
=================================================
鼠标点击获取数据:
[x y Iseffect]=ginput(点数)
Iseffect返回点击是否有效
不输入点数则按回车后才结束
或者用[x y]=getpts(fig)
=================================================
图片中用data cursor选取多个数据:
alt+点击左键
=================================================
隐藏坐标轴:
set(gca,’visible’,’off’)
=================================================
三维绘图旋转开启:
rotate3d on
=================================================
等高线:
contour(z)
contour(z,条数)
contour(z,指定高度)
注:z至少2×2以上
=================================================
绘制伪彩色图:
pcolor(z)
shading interp;%用于伪彩色图或者surf之类的插值
=================================================
等高线数值标注:
=contour(peaks);
clabel(c,h);
colorbar;
=================================================
产生球体:
[X,Y,Z] = sphere;
Origin = rand(1,3);
surf(X*R+Origin(1),Y*R+Origin(2),Z*R+Origin(3));
=================================================
向量图:(比如用于描述磁场之类的)
quiver(U,V)
quiver(X,Y,U,V)
示例:
[X,Y] = meshgrid(-2:.2:2);
Z = X.*exp(-X.^2 – Y.^2);
[DX,DY] = gradient(Z,.2,.2);
contour(X,Y,Z)
hold on
quiver(X,Y,DX,DY)
=================================================
三维画表面图:
mesh:网格
surf:表面
meshc,surfc:配上等高线
surfl:光源效果
光源位置:light(‘position’,[-3,-1,3],’style’,’local’)
=================================================
mesh,surf挖空方法:
[X,Y,Z]=peaks(25);
index=find(X<0&Y<0);
Z(index)=NaN;
surf(X,Y,Z);
=================================================
瀑布图:(沿着某个方向为线条形式的图)
[x y z]=peaks(30);
waterfall(x,y,z)
=================================================
三维网格图透明设置:
hidden
也可以help alpha
=================================================
rgbplot(x)
画红绿蓝三条曲线,x必须是M×3的矩阵。
=================================================
旋转颜色映射产生动画效果:
spinmap
=================================================
播放电影方式播放动画:(内存消耗严重)

for i=1:N
 plot_command
 m(:,i)=getframe;
end
movie(m)

=================================================
更新y值方式播放动画:

t=0:0.05:10*pi;
h=plot(t,sin(2*t).*exp(-t/5),'EraseMode','xor');
for i=1:200 
 y=sin(2*t+i/10).*exp(-t/5);
 set(h,'ydata',y);
 drawnow; 
end 

如果EraseMode为none,则全部轨迹保留(别的选项还有normal,background)
记得要开双缓冲set(gcf,’DoubleBuffer’,’on’),原理应该是和MFC一样
=================================================
动画保存为avi:

aviobj = avifile('animation.avi','fps',3); 
for k=1:25
 h = plot(fft(eye(k+16)));
 set(h,'EraseMode','xor');
 axis equal;
 frame = getframe(gca);
 aviobj = addframe(aviobj,frame);
end
aviobj = close(aviobj); 

=================================================
获取子窗口位置:

get(h1,’Position’);
=================================================
获取子窗口边界:

get(h1,’TightInset’);
=================================================
构造矩形框实例:

annotation(‘rectangle’,[x1,y1,w,h],’FaceAlpha’,.2,’FaceColor’,’red’,’EdgeColor’,’red’);
=================================================
构造双箭头:

annotation(‘doublearrow’,[0 0.5],[0 0.3])
=================================================
获取属性值:

get(h, ‘MarkerSize’)
=================================================
获取父对象:

ph=get(m, ‘Parent’) ;
=================================================
获取对象的所有属性值:

get(h)
=================================================
删除句柄对象:

delete(h)

=================================================
查看一个属性的所有可能值:

set(h,’属性’)

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

查找对象句柄:

b_handles=findobj(gca,’Color’,’b’);
h = findobj(gca,’type’,’line’)
=================================================

找到句柄后打开编辑界面:

inspect(b_handles)
=================================================
元胞转矩阵:

cell2mat
=================================================
figure全屏:

set(gcf,’outerposition’,get(0,’screensize’));
=================================================
鼠标点击函数:

d=plot(rand(5));
set(d,’ButtonDownFcn’,’set(gcbo,”Color”,”r”,”linew”,5)’) ;
%gcbo为鼠标点击返回值
=================================================
关闭figure时执行的函数:
fig=plot(rand(10));
set(fig1,’closerequestfcn’,’my_closereq’)
然后编写my_closereq:
selection = questdlg(‘Close Specified Figure?’, ‘Close Request Function’,…
‘Yes’,’No’,’Yes’);
switch selection
case ‘Yes’
delete(gcf)
case ‘No’
return
end
=================================================
自己绘制figure界面光标示例:
P = ones(16)+1;
P(1,:) = 1; P(16,:) = 1;
P(:,1) = 1; P(:,16) = 1;
P(1:4,8:9) = 1; P(13:16,8:9) = 1;
P(8:9,1:4) = 1; P(8:9,13:16) = 1;
P(5:12,5:12) = NaN;
set(gcf,’Pointer’,’custom’,’PointerShapeCData’,P,…
‘PointerShapeHotSpot’,[9 9])
=================================================
画图论那种图
gplot(A,Coordinates)画图的顶点,其中Coordinates是代表顶点的坐标,Coordinates是n*2矩阵,A是n*n的邻接矩阵,n是顶点的个数。
示例:k = 1:30;
[B,XY] = bucky;
gplot(B(k,k),XY(k,:),’-*’)
=================================================
构造坐标轴:
axes_handles(1)=axes(‘position’,[0.1 0.05 0.2 0.2]);
=================================================
字符串转元胞:
cellstr
=================================================
字符创所代表的matlab的值:
eval(‘linspace(0,2,100)’)
如果GUI生成可执行文件时,则必须用feval
=================================================
查找工作空间中的变量:
evalin(‘base’,’who’)
=================================================
工作空间变量赋值:
assignin(‘base’,’name’,Value)
=================================================
批量创建和计算变量:
for n = 1:12
eval([‘M’ num2str(n) ‘ = magic(n)’])
end
=================================================
字符串计算实例:
surf(x,y,eval(string))
=================================================
同次项合并:
collect
=================================================
字符串转表达式:
sym(string)
=================================================
获取时间字符串:
datestr(now)
current_t = datestr(clock,’mmm.dd,yyyy HH:MM:SS’)
=================================================
打开保存文件对话框:
[FileName,PathName] = uiputfile(‘*.jpg’,’Save File’);
file = strcat(PathName,FileName);
=================================================
打开open对话款:
file = uigetfile(‘*.fig’);
if ~isequal(file,0)
open(file);
end
=================================================
整合方式构造结构体:
c = {‘tree’,37.4,’birch’};
f = {‘category’,’height’,’name’};
s = cell2struct(c,f,2);
>> s.category
ans =
tree

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

正则表达式:

regexp(str,pattern,mode)

pattern通配符用.*?
=================================================

生成制作动画:

figure
axis equal
axis([-1 1 -1 1]*1.1)
set(gca, 'XTick', -1:0.5:1, 'YTick', -1:0.5:1)
grid on
set(gca, 'NextPlot', 'replaceChildren')
n = 100;
t = linspace(0, 2*pi, n);
M = moviein(n);
for i = 1 : n
    x = cos(t(1:i));
    y = sin(t(1:i));
    plot(x, y)
    M(i) = getframe;
end
movie(M)

=================================================
制作gif:

for i = 1 : 250
    plot(...)
    
    f=getframe(gcf);  
    imind=frame2im(f);
    [imind,cm] = rgb2ind(imind,256);
    %第一次必须创建!
    if i==1
        imwrite(imind,cm,file_name,'gif', 'Loopcount',inf,'DelayTime',0.01);
    else
        imwrite(imind,cm,file_name,'gif','WriteMode','append','DelayTime',0.01);
    end
end

此分界线下面为GUI部分:

uicontrol:Style:

[ {pushbutton} | togglebutton | radiobutton | checkbox | edit | text | slider | frame | listbox | popupmenu ]
=================================================
popup控件:
设置选项:
‘string’,’a|b|c’
获取选项:
get(h,Value),返回值:1,2,3…
=================================================
uimenu:
f=uimenu(gcf,’Label’, ‘XXX’,’Callback’, ‘XXXX’);
子菜单:
f1=uimenu(f,…..);
position=1,2,3可以指定位置
快捷键:
label中加&(结果为alt+按键)
=================================================
鼠标右键出现的菜单:
uicontextmenu,用法同menu
rwm=uicontextmenu;
uimenu(rwm,’Label’,’XXX’…)
=================================================
竖着的slider

修改宽高比
=================================================
复选框:
set(handles.XX,’checked’,’on’)%or ‘off’
=================================================
Import菜单功能:
callback中填写uiimport
=================================================
print菜单功能:
callback中填写printdlg
=================================================
退出的菜单功能:

selection = questdlg(['是否关闭',get(gcf,'Name'),'窗口'], ...
                     ['Close ',get(gcf,'Name'),'...'], ...
                     '是','否','是');
if strcmp(selection,'否')
    return;
else
    delete(gcf);
end

=================================================
help菜单:
写一个html文件,然后:
wed([‘file:’ which(‘XXX.html’)])
=================================================
ToggleButton/CheckBox:

if get(gcbo,'Value')==1;
    %TODO
else
	%TODO
end

=================================================
ListBox:
获取字符串:
get(h,’string’)
获取选中的索引:
get(h,’value’)
=================================================
RadioButton批量设置值为0:
将各个句柄值设置为:Radio_h(1),Radio_h(2)…

if get(gcbo,'Value')==1
	set(Radio_h(Radio_h ~= gcbo), 'value',0)
end

=================================================
EditText多行输入:
Max设置为2(保证Max-min>1)
=================================================
ListBox多选:
Max设置为2(保证Max-min>1)
=================================================
GUI生成exe
mcc -m xxxx
执行exe文件:!xxxx
=================================================
统一管理GUI CallBack函数:

function gui_fcn(action)
switch action
    case 'Close'
    case 'Peaks'
    case 'Export'
    otherwise
end

callback中填写类似:gui_fcn Close
=================================================
鼠标移动到控件上的提示字符串:
tooltipstring
=================================================
添加图片:
himge = findobj(‘tag’,’pic1′);
axes(himge);
logo = imread(‘1.jpg’);
image(logo);
set(himge,’visible’,’off’)
set(himge,’handlevisibility’,’off’)
=================================================
图标显示在按钮上:
A = imread(‘2.jpg’);
bu = findobj(‘tag’,’logobutton’);
set(bu,’cdata’,A);
=================================================
对于figure,等待按键:

fig_h=figure(1);
waitforbuttonpress;%(阻塞)
if get(fig_h,'CurrentCharacter')==13
	%todo
end

按键:tab(9),回车(13),ESC(17),上下左右(28-31),空格(32)
code = double(get(fig_h,’CurrentCharacter’))
对于waitforbuttonpress,返回0表示有鼠标点击,返回1表示键盘按键
=================================================
获取按键
function figure1_KeyPressFcn(hObject, eventdata, handles)
key = get(hObject,’CurrentCharacter’);
如果不在KeyPressFcn中,则是无时无刻都在等待获取,比如

while double(get(F,'CurrentCharacter'))~=27
    set(edit1,'String',datestr(now));
    pause(.1);
end

=================================================
currentkey:
返回值与CurrentCharacter不同,比如上下左右返回是uparrow,downarrow等,F1返回是f1,小键盘数字键1返回是numpad1等。
=================================================
selectiontype:
还可以返回alt,shift等按键信息
返回extent表示shift+左键或同时按下左右键
返回normal表示左键
返回alt表示alt或者右键
返回open表示双击左键或者右键
=================================================
currentpoint:
返回鼠标最后单击或者释放的位置
=================================================
进度条:

h = waitbar(0,'进行中');
for i = 1 :10000
    waitbar(i/10000,h);
end
close(h)

=================================================
群组按钮实例:(可用于制作工具栏)

fig=figure('Position',[200 200 250 120],'Name','btngroup 絛ㄒ',...
    'NumberTitle','off','Menubar','none');
icons = ['text(.5,.5,''B1'',''HorizontalAlignment'',''center'')'
    'text(.5,.5,''B2'',''HorizontalAlignment'',''center'')'];
callbacks = ['disp(''B1'')';'disp(''B2'')'];
btngroup(fig,'GroupID', 'TestGroup', 'ButtonID', ['B1';'B2'], 'Callbacks', callbacks, ...
'Position', [.4 .45 .25 .3], 'IconFunctions', icons);

=================================================
按下左键开始才开始定义消息函数:
建立m文件:

function mouse(action)
switch action
    case 'start'
        set(gcbf,'windowbuttonmotionfcn','mouse move');
        set(gcbf,'windowbuttonupfcn','mouse stop');
    case 'move'
        point = get(gca,'CurrentPoint');
        %%%%%%%%%%%%%%%%
    case 'stop'
        set(gcbf,'windowbuttonmotionfcn','');
        set(gcbf,'windowbuttonupfcn','');
end

在axis的 buttondownfcn中写:mouse start
=================================================
设置F1的函数:
set(gcf,’HelpFcn’,’XXXXXX’);
=================================================
listbox显示当前目录下的所有文件列表,点击并加载文件
list_h=uicontrol(‘style’, ‘listbox’,’Position’,[25 10 200 250]);
d=dir;
set(list_h,’string’,{d.name},’Callback’,…
[‘Value = get(gcbo,”Value”);’,…
‘String = get(gcbo,”String”);’,…
‘String = cellstr(String);’,…
‘uiimport(String{Value})’]);
=================================================
二维列表:
f = figure;
data = rand(3);
colnames = {‘X-Data’, ‘Y-Data’, ‘Z-Data’};
t = uitable(f, ‘Data’, data, ‘ColumnName’, colnames, …
‘Position’, [20 20 260 100]);
=================================================
阵列方式来排控件示例:
figure(‘name’, ‘uiarray’, ‘numbertitle’, ‘off’);
figPos = get(gcf, ‘pos’);
bigFramePos = [0 0 figPos(3) figPos(4)];
m = 4; n = 3;
border = 20; spacing = 10;
style = str2mat(‘push’, ‘slider’, ‘radio’, ‘popup’, ‘check’);
callback = ‘disp([”This is a ” get(gco, ”style”)])’;
string = str2mat(‘one’, ‘two’, ‘three’, ‘four-1|four-2|four-3’, ‘five’);
uiarray(bigFramePos, m, n, border, spacing, style, callback, string);
=================================================
文件夹树控件:
uitree(‘root’,’d:’);
uitree(‘root’,0)可以构造关于控件关系的树
=================================================
超简易选择对话框:
select = menu(‘提示信息’,’选项1′,’选项2′);
=================================================
提示对话框:(换行用n)
msgbox(‘信息标题’,’对话框标题’,’help’)
msgbox(‘信息标题’,’对话框标题’,’warn’)
msgbox(‘信息标题’,’对话框标题’,’error’)
msgbox(‘信息标题’,’对话框标题’,’custom’)%自己设计图标
示例:
Data=1:256;Icon=(Data’*Data)/128;
msgbox(‘信息标题’,’对话框标题’,’custom’,Icon,copper(128))
=================================================
模态对话框方式:
h = msgbox(‘信息标题’,’对话框标题’);
waitfor(h);
=================================================
设置对话框背景颜色:
set(h,’color’,’w’);
=================================================
修改提示对话框字体:
通过findall语句来实现:
hm=msgbox(‘信息标题’,’对话框标题’,’error’);
set(hm,’color’,’w’);
th=findall(hm,’Type’,’Text’);
set(th,’color’,’r’);
set(th,’FontSize’,24);
=================================================
问题选择对话框:(返回的是字符串)
Button=questdlg(‘请选择’,’标题’,’选项0′, ‘默认选项’,’选项2′,’默认选项’);
最多3个选项
=================================================
输入对话框:
answer=inputdlg(提示语,dlgTitle,对话框间距,默认值);
多个需要输入的选项提示语可以用{‘问题1′,’问题2’},返回值答案用answer{i}
=================================================
输入对话框编辑cancel选项:

if isempty(answer)
	XXXXXXXXX
end

=================================================
列表选择对话框:
str = {‘A’, ‘B’, ‘C’, ‘D’, ‘E’};
[s,ok] = listdlg(‘PromptString’,’请选择’,’name’,’title’,’SelectionMode’,’single’,…
‘ListString’,str, ‘fus’,10, ‘ListSize’,[160 80]);
ok为1表示有选,0表示没有选择
s是索引
其中okstring,cancelstring设置按钮的文字
=================================================
设置颜色对话框:
text_handle=uicontrol(‘Style’,’text’,’Position’,[250 250 120 20],…
‘String’,’被设置的text’);
uisetcolor(text_handle,’标题’);
=================================================
设置字体对话框:
figure;
hText=gtext(‘12345’);
uisetfont(hText, ‘Update Font’);
=================================================
添加工具栏图标:
uipushtool(‘Separator’,’on’,’TooltipString’,’提示信息’,…
‘ClickedCallback’,’msgbox(”XXX”,”XXXX”)’,’CData’,repmat(magic(12)/12^2,[1 1 3]));
=================================================
偏好设置对话框:
uigetpref
=================================================
设置定时器:
t = timer(‘Period’,1.0,’ExecutionMode’,’fixedrate’,’StartDelay’,0.5,’timerfcn’,’XXXX’);
start(t);
timerfcn调用方法:{‘functionname’,par1,par2…}
functionname的定义是:function functionname(t,event,para1,para2…)
timer中tasksexecuted表示重复执行的次数


【未完,随时更新】

本文内容遵从CC版权协议,转载请注明出自http://www.kylen314.com

分类: Matlab 标签:
  1. ╮(╯▽╰)╭
    2016年8月29日21:47 | #1

    原来你知道timer么,抄下来不会用还是没办法

验证码:3 + 3 = ?

友情提示:留言可以使用大部分html标签和属性;

添加代码示例:[code lang="cpp"]your code...[/code]

添加公式请用Latex代码,前后分别添加两个$$