MATLAB基础运算【9】:函数定义与封装

系列更新MATLAB各种运算和操作的说明。

本篇主要包括定义函数相关内容(可利用侧边目录直接定位):

  1. 查询分类并返回
  2. 参数输入数量的改变
  3. 声明函数注释与查询注释
  4. 定义函数的好处之一:运算效率
  5. 实例演练:GUI计算器设计

前文:

MATLAB基础运算【1】:矩阵元素

MATLAB基础运算【2】:矩阵运算

MATLAB基础运算【3】:微积分运算

MATLAB基础运算【4】:图像绘制

MATLAB基础运算【5】:图像绘制学科专题

MATLAB基础运算【6】:插值拟合与数值微积分

MATLAB基础运算【7】:代数运算

MATLAB基础运算【8】:数据及图像类型、数学操作、查询

函数封装是一种好习惯~ 容易修改、容易找错、使用方便、程序可读性高 ^ ^

1- 查询分类并返回

例:某校的课程时间如下:

1

2

3

4

5

6

8:00-9:35

9:50-11:25

13:30-15:05

15:20-16:55

17:05-18:40

19:20-20:55

       编写函数显示课程时间,要求:输入参数为x,x表示第x节课,当x不在范围内时,报错并退出;输出第x节课的时间;使用switch语句实现。

函数:注意函数定义文件名称需要与函数名称相同,后同

function [f] = classtime(x)
    % classtime显示某节课的时间
    % 输入x代表第x节课,当x不在范围内时,报错并退出

    switch x
        case 1
            disp('8:00-9:35');
        case 2
            disp('9:50-11:25');
        case 3
            disp('13:30-15:05');
        case 4
            disp('15:20-16:55');
        case 5
            disp('17:05-18:40');
        case 6
            disp('19:20-20:55');
        otherwise
            disp('error');
    end
end

命令行输入:

声明查询:

2- 参数输入数量的改变

例:编写函数Exp_Plot,做出y(x)=exp(x)的函数图像。定义域由输入参数决定:

如果有两个输入参数 a,b(a<b),则在区间[a,b]内作图;

如果只有一个输入参数 a,则在区间[a,a+10]内作图;

如果没有输入参数,则默认在区间[0,10]内作图。

函数:

function varargout = Expplot(varargin)
    % plot the image of exp
    % Expplot.m

    n = numel(varargin);
    if(n == 0)
        x = 0:0.05:10;
        varargout = plot(x, exp(x));
    elseif(n == 1)
        x = varargin{1}:0.05:varargin{1} + 10;
        varargout = plot(x, exp(x));
    elseif(n == 2)
        x = varargin{1}:0.05:varargin{2};
        varargout = plot(x, exp(x));
    end
end

命令行输入:Expplot(1,2)

图像:

命令行输入:Expplot()

图像:

命令行输入:Expplot(-5)

图像:

3- 声明函数注释与查询注释

在定义函数时使用注释行即可

例:

function f = Sphere1(r)
    % Sphere1函数计算半径为r的球的体积
    % 程序员姓名: 费曼
    % 代码编辑日期: 2024年13月32日
    % Sphere1.m

    f = 4 * (pi * r^3) / 3;
end

查询时使用help可查询函数声明信息

命令行输入:help Sphere1

返回:

Sphere1函数计算半径为r的球的体积

程序员姓名:费曼

代码编辑日期:2024年13月32日

Sphere1.m

命令行输入:lookfor Sphere1

返回:

Sphere1                                        - 函数计算半径为r的球的体积

注:虽然matlab函数名称区分大小写,但是用Sphere函数存储到正确路径后help函数搜索出来的还是sphere函数的说明,所以在此使用Sphere1作为函数名称作区分。

4- 定义函数的好处之一:运算效率

 自定义函数可以改变输入变量的数量,必要的时候可以

例:已知向量X_n=\{1,2,...,n\}, n=10^5,分别按照以下方式编写程序计算X_n^2,并使用tic/toc比较计算时间。

1)使用for循环对每个元素进行计算

2)使用matlab中的向量操作及自带函数,直接对向量X_n进行操作

函数:

function f = Xn2(Xn)
    % 计算向量Xn的平方
    % Xn2.m
    sum = 0;
    for i = 1:length(Xn)
        sum = sum + Xn(i)^2;
    end
    f = sum;
end

命令行输入:

Xn = 1:1:10^5;
tic
Xn2(Xn);
t = toc

返回值为:16.06574...

直接命令行输入:

Xn = 1:1:10^5;
tic
Xn*Xn';
t = toc

返回值为:19.0682896...

计算时间a小于b,说明定义函数用for循环计算在该题目中速度更快。

5- 实例演练:GUI计算器设计

例:设计GUI计算器

参考:

MATLAB·gui设计简单计算器应用实例_matlab用gui返回计算式子和答案-CSDN博客

(设计界面)(使用界面)

体会GUI设计的乐趣 =U=

初始代码:

function varargout = calculater(varargin)

% 开始初始化代码 - 不要编辑
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @calculater_OpeningFcn, ...
                   'gui_OutputFcn',  @calculater_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
% 结束初始化代码 - 不要编辑

说明:这段代码是一个 MATLAB GUI 应用程序的框架,用于创建和管理图形用户界面。代码中包含了一些注释,说明了函数的不同用途和行为。calculater 函数是 GUI 的入口点,它处理创建 GUI、响应用户交互和维护 GUI 状态等任务。代码中还包含了对 GUIDE 工具的引用,GUIDE 是 MATLAB 提供的一个用于设计 GUI 的工具。

function calculater_OpeningFcn(hObject, eventdata, handles, varargin)
% 此函数没有输出参数,参见 OutputFcn。
% hObject    图形对象的句柄
% eventdata 保留 - MATLAB 未来版本中定义
% handles    包含句柄和用户数据的结构(见 GUIDATA)
% varargin   传递给 calculater 的命令行参数(见 VARARGIN)
handles.output = hObject;
% 更新 handles 结构
guidata(hObject, handles);

% --- 从此函数输出的返回到命令行。
function varargout = calculater_OutputFcn(hObject, eventdata, handles) 
% varargout  返回输出参数的单元格数组(见 VARARGOUT);
% hObject    图形对象的句柄
% eventdata 保留 - MATLAB 未来版本中定义
% handles    包含句柄和用户数据的结构(见 GUIDATA)
varargout{1} = handles.output;


% --- 在对象创建期间执行,所有属性设置之后。
function edit1_Callback(hObject, eventdata, handles)
% hObject    edit1 的句柄(见 GCBO)
% eventdata 保留 - MATLAB 未来版本中定义
% handles    包含句柄和用户数据的结构(见 GUIDATA)
% 提示:get(hObject,'String') 返回 edit1 的内容作为文本
%        str2double(get(hObject,'String')) 返回 edit1 的内容作为双精度数字


% --- 在对象创建时执行,设置所有属性之后。
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    edit1 的句柄(见 GCBO)
% eventdata 保留 - MATLAB 未来版本中定义
% handles    空 - 在所有 CreateFcns 调用之后才创建句柄
% 提示:在 Windows 上,编辑控件通常有白色背景。
%       参见 ISPC 和 COMPUTER。
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
  • calculater_OpeningFcn:当 GUI 变得可见之前执行,用于初始化 GUI。
  • calculater_OutputFcn:用于从 GUI 返回输出到命令行。
  • edit1_Callback:当用户与 edit1 文本框交互时执行,例如输入文本或改变文本框的内容。
  • edit1_CreateFcn:在创建 edit1 文本框时执行,用于设置文本框的初始属性,如背景颜色。

编辑按钮示例:

% --- 在 pushbutton1 按钮按下时执行。
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    pushbutton1 的句柄(见 GCBO)
% eventdata 保留 - MATLAB 未来版本中定义
% handles    包含句柄和用户数据的结构(见 GUIDATA)
textString = get(handles.edit1, 'String'); % 获取 edit1 文本框的当前文本
textString = strcat(textString, '7'); % 将 '7' 追加到文本末尾
set(handles.edit1, 'String', textString); % 更新 edit1 文本框的文本


% --- 在 pushbutton2 按钮按下时执行。
function pushbutton2_Callback(hObject, eventdata, handles)
textString = get(handles.edit1, 'String'); % 获取 edit1 文本框的当前文本
textString = strcat(textString, '8'); % 将 '8' 追加到文本末尾
set(handles.edit1, 'String', textString); % 更新 edit1 文本框的文本

%...依此类推

% 删除最后一位
function pushbutton13_Callback(hObject, eventdata, handles)
textString = get(handles.edit1, 'String'); % 获取 edit1 文本框的当前文本
str = char(textString); % 将文本转换为字符数组
value = length(str); % 获取字符数组的长度
textString = str(1:value-1); % 从字符数组中删除最后一个字符
set(handles.edit1, 'String', textString); % 更新 edit1 文本框的文本


% 结果“=”
function pushbutton16_Callback(hObject, eventdata, handles)
textString = get(handles.edit1,'String');
ans = eval(textString);
set(handles.edit1,'String',ans);
  • pushbutton1_Callback:当用户点击数字 "7" 的按钮时执行,将数字 "7" 添加到 edit1 文本框的当前内容中。
  • pushbutton2_Callback:当用户点击数字 "8" 的按钮时执行,将数字 "8" 添加到 edit1 文本框的当前内容中。
  • ...剩下按钮依此类推
  • 删除最后一位文本和计算结果等按钮需要额外的命令操作。

实际效果:举例计算1.2*10:

 →→→ 

完整代码:

function varargout = calculater(varargin)
% CALCULATER MATLAB code for calculater.fig
%      CALCULATER, by itself, creates a new CALCULATER or raises the existing
%      singleton*.
%
%      H = CALCULATER returns the handle to a new CALCULATER or the handle to
%      the existing singleton*.
%
%      CALCULATER('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in CALCULATER.M with the given input arguments.
%
%      CALCULATER('Property','Value',...) creates a new CALCULATER or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before calculater_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to calculater_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 calculater

% Last Modified by GUIDE v2.5 05-Nov-2023 13:42:40

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @calculater_OpeningFcn, ...
                   'gui_OutputFcn',  @calculater_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 calculater is made visible.
function calculater_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 calculater (see VARARGIN)

% Choose default command line output for calculater
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes calculater wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = calculater_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;



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 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)
textString = get(handles.edit1,'String');
textString = strcat(textString,'7');
set(handles.edit1,'String',textString);


% --- Executes on button press in pushbutton2.
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)
textString = get(handles.edit1,'String');
textString = strcat(textString,'8');
set(handles.edit1,'String',textString);


% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
textString = get(handles.edit1,'String');
textString = strcat(textString,'9');
set(handles.edit1,'String',textString);


% --- Executes on button press in pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
textString = get(handles.edit1,'String');
textString = strcat(textString,'4');
set(handles.edit1,'String',textString);


% --- Executes on button press in pushbutton5.
function pushbutton5_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
textString = get(handles.edit1,'String');
textString = strcat(textString,'5');
set(handles.edit1,'String',textString);


% --- Executes on button press in pushbutton6.
function pushbutton6_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
textString = get(handles.edit1,'String');
textString = strcat(textString,'6');
set(handles.edit1,'String',textString);


% --- Executes on button press in pushbutton7.
function pushbutton7_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton7 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
textString = get(handles.edit1,'String');
textString = strcat(textString,'1');
set(handles.edit1,'String',textString);


% --- Executes on button press in pushbutton8.
function pushbutton8_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton8 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
textString = get(handles.edit1,'String');
textString = strcat(textString,'2');
set(handles.edit1,'String',textString);


% --- Executes on button press in pushbutton9.
function pushbutton9_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton9 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
textString = get(handles.edit1,'String');
textString = strcat(textString,'3');
set(handles.edit1,'String',textString);


% --- Executes on button press in pushbutton10.
function pushbutton10_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton10 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
set(handles.edit1,'String','');


% --- Executes on button press in pushbutton11.
function pushbutton11_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton11 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
textString = get(handles.edit1,'String');
textString = strcat(textString,'/');
set(handles.edit1,'String',textString);


% --- Executes on button press in pushbutton12.
function pushbutton12_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton12 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
textString = get(handles.edit1,'String');
textString = strcat(textString,'*');
set(handles.edit1,'String',textString);


% --- Executes on button press in pushbutton13.
function pushbutton13_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton13 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
textString = get(handles.edit1,'String');
str = char(textString);
value = length(str);
textString = str(1:value-1);
set(handles.edit1,'String',textString);


% --- Executes on button press in pushbutton14.
function pushbutton14_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton14 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
textString = get(handles.edit1,'String');
textString = strcat(textString,'+');
set(handles.edit1,'String',textString);


% --- Executes on button press in pushbutton15.
function pushbutton15_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton15 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
textString = get(handles.edit1,'String');
textString = strcat(textString,'-');
set(handles.edit1,'String',textString);


% --- Executes on button press in pushbutton16.
function pushbutton16_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton16 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
textString = get(handles.edit1,'String');
ans = eval(textString);
set(handles.edit1,'String',ans);


% --- Executes on button press in pushbutton17.
function pushbutton17_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton17 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
textString = get(handles.edit1,'String');
textString = strcat(textString,'0');
set(handles.edit1,'String',textString);


% --- Executes on button press in pushbutton18.
function pushbutton18_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton18 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
textString = get(handles.edit1,'String');
textString = strcat(textString,'.');
set(handles.edit1,'String',textString);

【本篇完】

  • 20
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值