【Math】MATLAB的安装、配置与科学计算 || 软件手册

【start:210125】

引言

在这里插入图片描述

MATLAB is a programming and numeric computing platform used by millions of engineers and scientists to analyze data, develop algorithms, and create models.

软件对比与适用范围

总结来说是:数值计算用matlab,解析计算用mathmatica,数据科学计算用python

MATLAB的基本配置

安装 MATLAB

【ref】MATLAB R2022b安装教程

注意,尽量安装b版本的matlab,因为一般b版本可以适配更高级的python,其中:
R2022a支持python 3.6
R2022b支持python 3.10

安装 MATLAB Add-Ons(附加功能)

有时执行代码出错时,matlab会提示我们:它需要额外的库:

*Note: You must have these MATLAB Add-Ons installed:

“Statistics and Machine Learning Toolbox”(https://www.mathworks.com/help/stats/)

“Image Processing Toolbox” (https://www.mathworks.com/help/images/)


这时,为了安装新的matlab库,第一种方法是:

直接点击matlab的install.exe程序(安装程序)来安装所需的库:

在这里插入图片描述


如果使用的是正版matlab,那么还有第二种更便捷的方法是:

直接在matlab软件里进行操作,在“主页”中点击“附加功能”,在点击“管理附加功能”,然后安装自己所需的库:

在这里插入图片描述

在这里插入图片描述

安装matlab app(直接用.mlappinstall文件安装)

欲安装打包好的matlab app,直接点击mlappinstall文件安装即可:

在这里插入图片描述

MATLAB的基本使用方法

将xxx文件夹添加到MATLB路径

要运行此文件,您可以更改MATLAB当前文件夹,或者将其文件夹添加到MATLAB路径。

在运行函数之前,一定要把 M 文件所在的目录添加到 MATLAB 的搜索路径中,或者将函数式文件所在的目录设置成当前目录,使 mm.m 所在目录成为当前目录,或让该目录处在 MATLAB 的搜索路径上。

或者,可以让 Matlab 自动变更路径,参考:

【ref】matlab运行包含子程序时自动变更路径方法

.m文件:函数式文件&命令式文件(脚本)

一个是function 定义的,叫函数;
另一个是脚本文件,执行的时候在matlab base内存空间运行。

在这里插入图片描述


【ref】MATLAB M文件详解

matlab的函数定义

下面是两个例子,一个包含函数定义,另一个是纯粹的脚本。

  1. 带有函数定义的例子:
function f = mm
    % This function demonstrates the use of "for" and creates a simple matrix
    for i = 1:4
        for j = 1:4
            a(i, j) = 1 / (i + j - 1);
        end
    end
    f = a;  % Output parameter of the function
end

在这个例子中,mm是一个函数,它创建了一个4x4的矩阵a,然后将其作为输出参数返回给调用者。

  1. 不带函数定义的例子:
% This script demonstrates the use of "for" and creates a simple matrix
for i = 1:4
    for j = 1:4
        a(i, j) = 1 / (i + j - 1);
    end
end

% You can directly display the matrix or perform other operations here
disp(a);

在这个例子中,没有函数定义,只有脚本。代码会直接创建矩阵a,并通过disp(a)在命令行窗口显示矩阵。这样的代码不具备独立的函数性质,只能按顺序执行。

matlab的函数调用

  • matlab读取函数要文件名还是函数名?

MATLAB中函数调用是通过文件名调用,所以函数文件名和文件里面的函数名,可以不一样,但是在命令窗口调用的是函数文件名。


  • matlab测试函数时,未定义变量,报错:输入参数的数目不足

自定义函数时,传递的都是形参,如果直接点击运行,没有传递实参给程序,也就“缺少参数”了。保存好自定义函数后,不要点击运行,在命令行窗口给定实参进行调用。

【ref】输入参数的数目不足?


  • 为函数设置默认参数

案例:

function [Ef Nv Nc mn]=Fermi_level_position_calculator_(Nd0, Na0,T,Ef0,Eg)
	% nargin 是 MATLAB 中的一个内置函数,用于返回当前正在执行的函数的输入参数个数。
    if nargin < 5
        disp('nargin<5')
        Nd0 = 1;  % Set your default value here
        Na0 = 1;
        T = 1;
        Ef0 = 1;
        Eg = 1;
    else
        disp('nargin=5')
        Nd0 = Nd0;
        Na0 = Na0;
        T = T;
        Ef0 = Ef0;
        Eg = Eg;
    end
end

或者:

function result = myFunction(a, b, c, d)
    % 设置所有参数的默认值
    if nargin < 1 || isempty(a)
        a = defaultAValue;
    end

    if nargin < 2 || isempty(b)
        b = defaultBValue;
    end

    if nargin < 3 || isempty(c)
        c = defaultCValue;
    end

    if nargin < 4 || isempty(d)
        d = defaultDValue;
    end

    % Rest of the function body
    % 使用 a、b、c、d 进行计算
end

matlab代码编辑器中缩进的自动对齐

从matlab2007开始,matlab编辑器通过全选+ Ctrl+i,可以对代码进行自动排版;

但初始设置有一个缺点:不能识别function,不会对function后的一行进行缩进——通过到matlab的英文论坛查询发现,可以通过设置使function后一行也能进行缩进。具体设置如下:

Preference->Editor/Debugger->Language->Function indenting format:Indent all functions(matlab2010b)

在这里插入图片描述
修改前:

function f=mm
%This file is devoted to demonstrate the use of "for"
%and to create a simple matrix
for i=1:4
    for j=1:4
        a(i,j)=1/(i+j-1);
    end
end
disp(a)
end

修改后:

function f=mm
    %This file is devoted to demonstrate the use of "for"
    %and to create a simple matrix
    for i=1:4
        for j=1:4
            a(i,j)=1/(i+j-1);
        end
    end
    disp(a)
end

【ref】matlab自动对齐

.mlx文件:新建实时脚本

直接在mlx里写入:

Fermi_level_position_calculator_(1,1,1,1,1)

PETE_net_current_calculator_(1,1,1,1,1,1,1,1,1,1,1)

PETE_IV_plotter_
  • 去掉mlx文件的单元格中绿色的箭头

解决方法:直接停止程序的运行

MATLAB的优势

工作区能直接展示丰富的数据统计

在这里插入图片描述

在python中使用matlab库

python import matlab

配置:在环境中安装matlab库

目标:把matlab视为python的一个库,在python中import matlab

方法:激活 python 环境,进入到指定路径:E:\CS\MATLAB R2022b(64bit)\MATLAB\R2022b\extern\engines\python,然后执行:python -m pip install .

这样就可以 import matlab 了:

import matlab
print(matlab)

返回:

<module 'matlab' from 'e:\\CS\\Anaconda3\\envs\\ai38\\lib\\site-packages\\matlab\\__init__.py'>

【ref】安装用于 Python 的 MATLAB Engine API

运行

报错

如果因为某种原因更新了matlab的目录,可能会发现找不到 ...R2022b\extern\engines\python

报错如下:

>>> import matlab
arch_file : F:\CS\Anaconda3\envs\physeg38\Lib\site-packages\matlab\engine\_arch.txt
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "F:\CS\Anaconda3\envs\physeg38\lib\site-packages\matlab\__init__.py", line 47, in <module>
    add_dirs_to_path(bin_folder, engine_folder, extern_bin)
  File "F:\CS\Anaconda3\envs\physeg38\lib\site-packages\matlab\__init__.py", line 19, in add_dirs_to_path
    raise RuntimeError("Could not find directory: {0}".format(engine_dir))
RuntimeError: Could not find directory: F:\CS\Matlab_R2022a(64bit)\MATLAB\R2022b\extern\engines\python\dist\matlab\engine\win64

F:\CS\Anaconda3\envs\physeg38\lib\site-packages\matlab\__init__.py 里打印arch_file的路径:

arch_file = os.path.join(package_folder, 'engine', '_arch.txt')
print(f'arch_file : {arch_file}')

然后调用matlab

import matlab

得到arch_file的路径:

# arch_file : F:\CS\Anaconda3\envs\physeg38\Lib\site-packages\matlab\engine\_arch.txt

然后在arch_file里修改 ...R2022b\extern\engines\python\dist\matlab\engine\win64 的路径即可

在vscode中调用matlab程序

配置:在vscode中安装matlab插件

安装 Matlab Unofficial 插件(而非MATLAB)

在这里插入图片描述

在 settings.json 下面输入下面这三行:

    "matlab.mlintpath":"E:\\CS\\MATLAB R2022b(64bit)\\MATLAB\\R2022b\\binwin64\\mlint.exe",
    "matlab.matlabpath": "E:\\CS\\MATLAB R2022b(64bit)\\MATLAB\\R2022b\\binmatlab.exe",
    "matlab.linterEncoding": "gb2312",

运行

运行后,可以成功弹出窗口(但是:反应会慢半拍;每次都会弹出新的命令行窗口,不会覆盖旧的窗口)
在这里插入图片描述

【ref】Vscode 配置 matlab 环境

优势互补:vscode写作&matlab运行

优势互补,效果最佳

在vscode中写代码

快捷键和vscode一致;

Ctrl+/注释方便;

Shift+Alt+↓快速复制某一行代码到下一行方便:

    disp(['err_with_variant_T: ', num2str(err_with_variant_T)]);
    disp(['left term: ', num2str(left_term)]);
    disp(['left 1: ', num2str(P_sun)]);
    disp(['left 2: ', num2str(J_rev*(phiB+2*Kb*TA))]);
    disp(['right term: ', num2str(right_term)]);
    disp(['right 1: ', num2str(P_IR)]);
    disp(['right 2: ', num2str(P_0)]);
    disp(['right 3: ', num2str(P_rad)]);
    disp(['right 4: ', num2str(J_emm*(phiB+2*Kb*TC))]);
    disp(['n q neq peq: ', num2str(n), ' ', num2str(q), ' ', num2str(neq), ' ', num2str(peq)]);

Ctrl+左键直接查看函数的定义;

可单击而非双击打开文件或文件;

在matlab中运行代码

可(无弹窗)直接在matlab界面中运行命令;

可直接查看所有函数的定义;

修改函数定义中的变量名时,可一键重命名所有变量;

MATLAB与科学计算

插值算法

griddedInterpolant 和 interp1

griddedInterpolantinterp1 是两种在 MATLAB 中进行插值操作的不同函数,它们的用法有所不同,具体如下:

%% griddedInterpolant方法(可运行)
x = 1:5;
y = 1:5;
y = y*10;

xi = 1.5;
F = griddedInterpolant(x, y);
result = F(xi);
disp(result)


%% interp1方法(可运行)
x = 1:5;
y = 1:5;
y = y*10;

xi = 1.5;
F = interp1(x, y, xi);
result = F;
disp(result)


%% interp1方法(不可运行)
x = 1:5;
y = 1:5;
y = y*10;

xi = 1.5;
F = interp1(x, y);
result = F(xi);
disp(result)

解一元方程

确定返回根的顺序

mathmatica的Solve和matlab的roots有什么不同?解一元方程时返回根的顺序是什么?
【mathmatica】ff = x /. Solve[aa*x^3 + bb*x^2 - cc*x - dd == 0, x];
【matlab】x = roots([aa, bb, -cc, -dd]);

在Mathematica的Solve函数中,根的顺序可能是根的任意排列,具体取决于内部算法。因此,在具体应用中,必须要亲自验证、确认结果的顺序是否符合需求(很多时候莫名其妙的虚数就是从这里算出来的)。

解微分方程

数值积分

MATLAB App案例

Mitometer App

【code】https://github.com/aelefebv/Mitometer

将pixal半径设置得过大,报错

警告: TIFF 库警告 - 'TIFFReadDirectory:  Unknown field with tag 50838 (0xc696) encountered.' 
警告: TIFF 库警告 - 'TIFFReadDirectory:  Unknown field with tag 50839 (0xc697) encountered.' 
警告: TIFF 库警告 - 'TIFFReadDirectory:  Unknown field with tag 50838 (0xc696) encountered.' 
警告: TIFF 库警告 - 'TIFFReadDirectory:  Unknown field with tag 50839 (0xc697) encountered.' 
数组索引必须为正整数或逻辑值。

出错 optimizeSigmaThresh (line 108)
threshOptimal = threshMatrix(floor(median(rowMin)));

出错 GUI2/Start2DButtonPushed (line 1098)
                    [app.sig,app.thr,costs] = optimizeSigmaThresh(ImBgRemoved);
 
错误使用 matlab.ui.control.internal.controller.ComponentController/executeUserCallback (line 382)
计算 Button PrivateButtonPushedFcn 时出错。

【ref】相同issue:Issue with pixel size

select highlighted 报错

函数或变量 'holdAllTemp' 无法识别。

出错 GUI2/SelecthighlightedButtonPushed (line 2014)
            app.holdAll = holdAllTemp;
 
错误使用 matlab.ui.control.internal.controller.ComponentController/executeUserCallback (line 382)
计算 Button PrivateButtonPushedFcn 时出错。

在这里插入图片描述

【ref】相同issue:Segmentation and tracking completed but nothing shows

MATLAB Debug

Debug commands only allowed when stopped in debug mode.

问题:为什么一直说我在matlab里使用了Debug命令?明明没有

解决方法:重启matlab即可

警告: 将图例条目限制为 50 个。指定图形对象的向量以显示 50 个以上的条目。

plot时出现上述命令,可能是横坐标选错了,比如:

plot(TC, Jemm-J_rev, 'LineWidth', 2, 'DisplayName', ['fixed n, xi = ', num2str(xi)]);

如果TC是一个数字,而不是一个列表,那么就可能会出现“图例数量爆炸”的情况

Matlab命令semilogy不起作用

原因:在使用semilogy命令之前不能使用 hold on 命令,hold on 命令要放到 semilogy 命令之后。

【ref】Matlab命令semilogy不起作用

文件被matlab占用时的删除方法

在命令行输入fclose all,之后就可以删除该文件了

  • 17
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值