概述
本资料所有问题及代码均摘选自matlab中文论坛,主要供自己学习使用。非常感谢论坛的所有提出以及解答问题的会员。
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 GUIDATA)
axes(handles.axes1); %取得axes1的句柄
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); %取得axes1的句柄
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
代码2
代码:
function varargout = matlab(varargin)
% MATLAB M-file for matlab.fig
% MATLAB, by itself, creates a new MATLAB or raises the existing
% singleton*.
%
% H = MATLAB returns the handle to a new MATLAB or the handle to
% the existing singleton*.
%
% MATLAB('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in MATLAB.M with the given input arguments.
%
% MATLAB('Property','Value',...) creates a new MATLAB or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before painter_OpeningFunction gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to matlab_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Copyright 2002-2003 The MathWorks, Inc.
% Edit the above text to modify the response to help matlab
% Last Modified by GUIDE v2.5 03-Oct-2009 17:01:36
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @matlab_OpeningFcn, ...
'gui_OutputFcn', @matlab_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before matlab is made visible.
function matlab_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to matlab (see VARARGIN)
% Choose default command line output for matlab
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes matlab wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.function varargout = matlab_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on mouse press over axes background.
function axes1_ButtonDownFcn(hObject, eventdata, handles)
% hObject handle to axes1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
mouse start
步骤是需要利用GUIDE添加一个Static和一个 Text Axes,然后添加Callback函数即可,即可实现如下的画笔功能。
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 GUIDATA)
selection = questdlg('Close This Figure?',...
'Close Request Function',...
'Yes','No','Yes');
switch selection,
case 'Yes',
delete(gcf)
case 'No'
return
end
至于窗口关闭可以如下:
代码:
function test %确认关闭右上脚的关闭按钮
figure;
set(gcf,'CloseRequestFcn',@my_closefcn);
function my_closefcn(src,evnt)
% User-defined close request function
% to display a question dialog box
selection = questdlg('Close This Figure?',...
'Close Request Function',...
'Yes','No','Yes');
switch selection,
case 'Yes',
delete(gcf)
case 'No'
return
end
现在考虑如何能将两者合二为一?
参数含义:
前者三个参数:
hObject------hObject handle to Untitled_10 (see GCBO);
eventdata ------reserved,to be defined in a future version of MATLAB;
handles------ handles structure with handles and user data (see GUIDATA)。
后者两个参数:
src------The handle of the object generating the callback (the source of the event) 理解同hObject;
event------The event data structure (can be empty for some callbacks)理解同eventdata;
如果写出如下语句set(gcf,'CloseRequestFcn',………
@Untitled_10_Callback);关闭窗口会发现报错如下:
??? Input argument "handles" is undefined.意思就是handles未定义,因为@my_function默认只有两个参数。可考虑按如下扩展一个参数:
代码:
set(gcf,'CloseRequestFcn',{@Untitled_10_Callback,handles});
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');
end
h=1;
ss='b';
qq=eomday(y,m);
for k=1:qq;
n=datenum(y,m,k);
[da,w] = weekday(n);
if k==d;
ss='r';
end
uicontrol(gcf,'style','push',...
'unit','normalized','position',[0.02+da*0.1,0.55-h*0.08,0.08,0.06],...
'BackgroundColor',0.6*[1,1,1],'ForegroundColor',ss,...
'String',num2str(k));
ss='b';
if da==7;
h=h+1;
end
end
uicontrol(gcf,'style','push',...
'unit','normalized','position',[0.6,0.66,0.12,0.08],...
'BackgroundColor',0.6*[1,1,1],'ForegroundColor',ss,...
'String','clock','fontsize',18,'fontname','times new roman');
Tq=uicontrol(gcf,'style','push',...
'unit','normalized','position',[0.74,0.66,0.17,0.08],...
'BackgroundColor',0.6*[1,1,1],'ForegroundColor',[0.1,0.9,0.9],...
'fontsize',18,'fontname','times new roman');
sq='The calendar';
uicontrol(gcf,'style','push',...
'unit','normalized','position',[0.14,0.86,0.37,0.08],...
'BackgroundColor',0.6*[1,1,1],'ForegroundColor',[0.1,0.9,0.9],...
'fontsize',18,'fontname','times new roman','string',sq);
try
while 1
set(Tq,'String',datestr(now,13));
pause(1);
end
end
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
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=%.3fn',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:matlabxyZ.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:matlabxyZ.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:matlabxyZ.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});
end
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;
clf
h=mesh(x1,y1,z1);
hold on;
surf(x,y,z);
xlabel('x');ylabel('y');zlabel('z');
set(gcf,'units','normalized','position',[0,0,1,1]);
pause(1);
end;
end
81、如何利用ode45解方程
function myname()
global m c k
m=1;
k=6;
c=2.5;
[T,Y]=ode45(@eqn1,[0,1],[0;0]);
plot(T,Y);
function xdot=eqn1(t,x)
xdot=[x(2);-6*x(1)-2.5*x(2)+1*(2*sin(t))];
end
end
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']);
end
x=1:k;
plot(x,y,'marker','.','markersize',12);
for ii=1:k
line([x(ii) x(ii)],[y(ii) 0]);
end
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';
k=1;
while n~=0
p(k)=rem(n,b);
n=fix(n/b);
k=k+1;
end
k=k-1;
strdec='';
while k>=1
kb=p(k);
strdec=strcat(strdec,ch1(kb+1:kb+1));
k=k-1;
end
dec=strdec;
set(ht,'string',num2str(dec));
end
function myclose(hobj,event)
close(hf);
end
end
89、matlab读取大数据文件的方法
function[t datafile]=readtxt1(filename)
fprintf('开始读取数据,请等待!n');
main_path = 'C:MATLAB7data';% 文件主路径
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:MATLAB7dataxue.txt', 'wt');% matrix data about signal
fidout2 = fopen('C:MATLAB7datashao.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:MATLAB7datashao.txt');
save C:MATLAB7datashao.mat shao
delete C:MATLAB7dataxue.txt
delete C:MATLAB7datashao.txt
load C:MATLAB7datashao.mat
datafile=zeros(size(shao,1),len);
t=shao(i,1);
datafile(:,i)=shao(i,2);
save C:MATLAB7datadatafile.mat
end
fprintf('读取数据结束。n');
代码:
clear;clc
filename=input('please input the shot number:');% input form of the shot number like :105871
main_path = 'C:MATLAB7data';% 文件主路径
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;
end
pause(1);
movie(F,100);% 播放视频200次
最后
以上就是失眠豆芽为你收集整理的Matlab资料汇总暨MATLAB中文论坛帖子整理(二)的全部内容,希望文章能够帮你解决Matlab资料汇总暨MATLAB中文论坛帖子整理(二)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复