MATLAB入门教程

MATLAB Documentationhttps://ww2.mathworks.cn/help/matlab/index.html?s_tid=CRUX_topnav

快捷键

Ctrl+i 格式化代码

Ctrl+R 多行注释

Ctrl+T 取消注释

命令

clear 清除工作区的所有变量

clc 清屏

基础操作与变量

变量定义与数据类型

MATLAB中字符数组与字符串数组的区别_matlab字符串数组和字符数组的区别-CSDN博客https://blog.csdn.net/houor/article/details/121622121

Matlab基础语法:变量和数据类型,基本运算,矩阵和向量,常用函数,脚本文件_matlab 变量类型-CSDN博客https://blog.csdn.net/weidl001/article/details/139759627?ops_request_misc=&request_id=&biz_id=102&utm_term=MATLAB%E5%8F%98%E9%87%8F%E7%B1%BB%E5%9E%8B&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-1-139759627.142^v102^pc_search_result_base3&spm=1018.2226.3001.4187

Matlab 复制代码
% 标量
a = 5;                  % 双精度浮点数
b = 3 + 4i;             % 复数
c = 'Hello';            % 字符数组
d = "World";            % 字符串

% 数组和矩阵
vector = [1, 2, 3, 4, 5];           % 行向量
matrix = [1, 2, 3; 4, 5, 6; 7, 8, 9]; % 3x3矩阵

% 特殊矩阵
zeros_mat = zeros(3, 4);    % 3x4零矩阵
ones_mat = ones(2, 3);      % 2x3全1矩阵
eye_mat = eye(4);           % 4x4单位矩阵
rand_mat = rand(2, 3);      % 2x3随机矩阵(0-1均匀分布)
randn_mat = randn(3, 3);    % 3x3正态分布随机矩阵

% 元胞数组(可存储不同类型数据)
cell_array = {1, 'text', [1, 2, 3], rand(2,2)};

% 结构体
person.name = 'feng';
person.age = 21;
person.scores = [85, 92, 78];

使用单引号是字符数组,双引号是字符串。

特性 字符数组 字符串
定义方式 单引号 'text' 双引号 "text"
数据类型 char string
空值表示 '' (0×0) "" (1×1)
拼接操作 [str1, str2] str1 + str2
内存效率 更高 稍低
函数支持 传统函数 现代函数
数组处理 需要元胞数组 原生支持

常用基础函数

下面代码正常运行需要把matrix,vector数组和矩阵进行定义。

Matlab 复制代码
% 显示和获取信息
disp('Hello MATLAB');       % 显示文本
whos                       % 显示工作区变量信息
size(matrix)               % 获取矩阵维度
length(vector)             % 获取向量长度
numel(matrix)              % 获取矩阵元素总数

% 数据类型转换
str = num2str(123);        % 数字转字符串
num = str2double('456');   % 字符串转数字
int_val = int8(100);       % 转换为8位整数

矩阵操作与运算

Matlab:矩阵运算篇------矩阵数学运算_矩阵除法-CSDN博客https://blog.csdn.net/m0_71824048/article/details/146128229?ops_request_misc=elastic_search_misc&request_id=0ae5f064f0f0afb3af04a72e88097ebd&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-1-146128229-null-null.142^v102^pc_search_result_base3&utm_term=MATLAB%E4%B8%AD%E7%9F%A9%E9%98%B5%E8%BF%90%E7%AE%97&spm=1018.2226.3001.4187

基本矩阵运算

Matlab 复制代码
A = [1, 2; 3, 4];
B = [5, 6; 7, 8];

% 算术运算
C = A + B;      % 矩阵加法
D = A - B;      % 矩阵减法
E = A * B;      % 矩阵乘法
F = A .* B;     % 元素对应相乘(点乘)
G = A / B;      % 矩阵右除(A*inv(B))
H = A \ B;      % 矩阵左除(inv(A)*B)
I = A .^ 2;     % 每个元素平方

% 矩阵函数
det_A = det(A);             % 行列式
inv_A = inv(A);             % 逆矩阵
rank_A = rank(A);           % 矩阵的秩
trace_A = trace(A);         % 矩阵的迹
[eig_vec, eig_val] = eig(A); % 特征值和特征向量

索引和切片

这里不是从0开始算索引。

Matlab 复制代码
M = magic(5);   % 创建5x5魔方矩阵

% 索引访问
element = M(2, 3);          % 第2行第3列元素
row = M(3, :);              % 第3行所有元素
column = M(:, 4);           % 第4列所有元素
submatrix = M(2:4, 1:3);    % 第2-4行, 第1-3列子矩阵

% 逻辑索引
idx = M > 20;               % 逻辑索引矩阵
large_values = M(idx);      % 获取大于20的元素

% 线性索引
linear_idx = M(6);          % 按列优先的第6个元素

流程控制

matlab程序设计------程序流程控制-CSDN博客https://blog.csdn.net/zhanghongyi_cpp/article/details/136715838?ops_request_misc=elastic_search_misc&request_id=4fdace35a60713836abfe1fcdba4bbf1&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-1-136715838-null-null.142^v102^pc_search_result_base3&utm_term=MATLAB%E4%B8%AD%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6&spm=1018.2226.3001.4187

条件语句

这个elseif是连着一起的,和其他编程语言本质上是一样的,就是关键字和写法上有的区别。

判断不等于使用的是:~=。

Matlab 复制代码
% if-elseif-else语句
x = 10;
if x > 0
    disp('正数');
elseif x < 0
    disp('负数');
else
    disp('零');
end

% switch语句
day = 'Monday';
switch day
    case {'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'}
        disp('工作日');
    case {'Saturday', 'Sunday'}
        disp('周末');
    otherwise
        disp('未知日期');
end

循环语句

循环也和其他语言类似,需要注意的是末尾需要end。

这里的i=1:10包括1和10

Matlab 复制代码
% for循环
sum_for = 0;
for i = 1:10
    sum_for = sum_for + i;
end

% while循环
sum_while = 0;
n = 1;
while n <= 10
    sum_while = sum_while + n;
    n = n + 1;
end

% 向量化操作(比循环更高效)
sum_vec = sum(1:10);

函数编程

函数定义与使用

MATLAB函数句柄详解-CSDN博客https://blog.csdn.net/edward_zcl/article/details/90231453MATLAB的编程与应用,匿名函数、嵌套函数、蒙特卡洛法的掌握与使用_matlab匿名函数-CSDN博客https://blog.csdn.net/Williamtym/article/details/134356032

Matlab 复制代码
% 在myFunction.m文件中定义函数
function [output1, output2] = myFunction(input1, input2)
    % 函数说明:计算两个数的和与积
    output1 = input1 + input2;
    output2 = input1 * input2;
end

% 调用函数
[a, b] = myFunction(3, 4);  % a=7, b=12

% 匿名函数
square = @(x) x.^2;
result = square(5);         % result=25

% 函数句柄
f = @sin;                   % 创建sin函数的句柄
y = f(pi/2);               % y=1

数据可视化

Matlab学习入门篇(五)------ 数据可视化_matlab可视化-CSDN博客https://blog.csdn.net/naibula/article/details/131660044?ops_request_misc=elastic_search_misc&request_id=3ebdc9c1e373b6015ce40d6767b33dcc&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-1-131660044-null-null.142^v102^pc_search_result_base3&utm_term=MATLAB%E4%B8%AD%E6%95%B0%E6%8D%AE%E5%8F%AF%E8%A7%86%E5%8C%96&spm=1018.2226.3001.4187

基本绘图函数

Matlab 复制代码
% 创建数据
x = linspace(0, 2*pi, 100);
y1 = sin(x);
y2 = cos(x);

% 线图
figure(1);
plot(x, y1, 'r-', 'LineWidth', 2);  % 红色实线
hold on;                            % 保持当前图形
plot(x, y2, 'b--', 'LineWidth', 2); % 蓝色虚线
xlabel('x');
ylabel('y');
title('正弦和余弦函数');
legend('sin(x)', 'cos(x)');
grid on;
hold off;

% 散点图
figure(2);
scatter(x(1:10:end), y1(1:10:end), 50, 'filled');
title('散点图示例');

% 直方图
figure(3);
data = randn(1000, 1);
histogram(data, 30);
title('正态分布数据直方图');

% 子图
figure(4);
subplot(2, 2, 1);
plot(x, y1);
title('子图1');

subplot(2, 2, 2);
plot(x, y2);
title('子图2');

subplot(2, 2, [3, 4]);
plot(x, y1 + y2);
title('子图3和4合并');

3D绘图

Matlab 复制代码
% 3D曲面图
[X, Y] = meshgrid(-2:0.1:2, -2:0.1:2);
Z = X .* exp(-X.^2 - Y.^2);

figure(5);
surf(X, Y, Z);
xlabel('X');
ylabel('Y');
zlabel('Z');
title('3D曲面图');
colorbar;

% 3D曲线图
t = linspace(0, 10*pi, 1000);
x = sin(t);
y = cos(t);
z = t;

figure(6);
plot3(x, y, z, 'LineWidth', 2);
grid on;
title('3D螺旋线');

文件I/O操作

读写数据文件

Matlab 复制代码
% 保存和加载.mat文件
data = rand(5, 5);
save('myData.mat', 'data');     % 保存变量到文件
clear data;                     % 清除变量
load('myData.mat');             % 从文件加载变量

% 读写文本文件
% 写入文本文件
fid = fopen('data.txt', 'w');
fprintf(fid, '%d %f %s\n', 1, 3.14, 'pi');
fclose(fid);

% 读取文本文件
fid = fopen('data.txt', 'r');
data_cell = textscan(fid, '%d %f %s');
fclose(fid);

% 读写Excel文件
% 写入Excel
xlswrite('data.xlsx', magic(5), 'Sheet1');

% 读取Excel
[num, txt, raw] = xlsread('data.xlsx', 'Sheet1');

% 读写CSV文件
% 写入CSV
csvwrite('data.csv', rand(3, 3));

% 读取CSV
csv_data = csvread('data.csv');

常用内置函数

数学函数

Matlab 复制代码
% 基本数学函数
abs_value = abs(-5);            % 绝对值
sqrt_value = sqrt(16);          % 平方根
exp_value = exp(1);             % 指数函数
log_value = log(10);            % 自然对数
log10_value = log10(100);       % 以10为底的对数

% 三角函数
sin_val = sin(pi/2);           % 正弦
cos_val = cos(pi);             % 余弦
tan_val = tan(pi/4);           % 正切

% 取整函数
round_val = round(3.6);        % 四舍五入
floor_val = floor(3.6);        % 向下取整
ceil_val = ceil(3.2);          % 向上取整
fix_val = fix(-3.6);           % 向零取整

% 统计函数
data = randn(100, 1);
mean_val = mean(data);         % 均值
median_val = median(data);     % 中位数
std_val = std(data);           % 标准差
var_val = var(data);           % 方差
max_val = max(data);           % 最大值
min_val = min(data);           % 最小值

字符串操作

Matlab 复制代码
% 字符串创建和连接
str1 = 'Hello';
str2 = 'MATLAB';
combined = [str1, ' ', str2];  % 字符串连接

% 字符串函数
length_str = length(str1);                 % 字符串长度
upper_str = upper(str1);                   % 转换为大写
lower_str = lower(str2);                   % 转换为小写
strcmp_result = strcmp(str1, str2);        % 字符串比较
find_str = strfind(combined, 'MAT');       % 查找子串
replace_str = strrep(combined, 'MATLAB', 'World'); % 替换子串

% 字符串分割和组合
split_str = split('a,b,c', ',');           % 分割字符串
join_str = join(split_str, '-');           % 组合字符串

高级功能

时间处理

Matlab 复制代码
% 当前时间
current_time = now;                % 当前日期时间(序列号)
datetime_str = datestr(now);       % 转换为字符串
datetime_obj = datetime('now');    % 创建datetime对象(R2014b+)

% 时间计算
start_time = datetime('2023-01-01');
end_time = datetime('2023-12-31');
duration = end_time - start_time;  % 时间间隔

% 计时
tic;                               % 开始计时
pause(2);                          % 暂停2秒
elapsed_time = toc;                % 获取经过时间

错误处理

Matlab 复制代码
% try-catch语句
try
    result = 1/0;                 % 可能出错的操作
catch ME
    disp(['错误发生: ', ME.message]);
    % 其他错误处理代码
end

% 警告处理
warning('这是一个警告消息');      % 发出警告
lastwarn('');                     % 清除最后警告

实用技巧和最佳实践

代码优化

Matlab 复制代码
% 预分配内存(提高循环效率)
n = 10000;
% 不好的做法(不预分配)
% result = [];
% for i = 1:n
%     result = [result, i^2];
% end

% 好的做法(预分配)
result = zeros(1, n);
for i = 1:n
    result(i) = i^2;
end

% 向量化操作(比循环更快)
result_vec = (1:n).^2;

% 使用逻辑索引
data = randn(1000, 1);
positive_data = data(data > 0);   % 获取正数元素

调试技巧

Matlab 复制代码
% 设置断点
% 在编辑器中点击行号左侧设置断点,或使用:
dbstop in myFunction at 10;   % 在myFunction第10行设置断点

% 调试命令
dbcont;     % 继续执行
dbstep;     % 单步执行
dbquit;     % 退出调试模式

% 检查变量
keyboard;   % 暂停执行,进入调试模式
相关推荐
蓝风破云1 小时前
C++实现常见的排序算法
数据结构·c++·算法·排序算法·visual studio
浩浩测试一下2 小时前
06高级语言逻辑结构到汇编语言之逻辑结构转换 for (...; ...; ...)
汇编·数据结构·算法·安全·web安全·网络安全·安全架构
野生的编程萌新5 小时前
【数据结构】从基础到实战:全面解析归并排序与计数排序
数据结构·算法·排序算法
躺平都躺不明白6 小时前
数学建模-灰色关联分析(GRA)
数学建模·matlab
凌晨7点7 小时前
拓展:simulink中将仿真环境离散化
matlab·simulink
whitepure7 小时前
万字详解常用数据结构(Java版)
java·数据结构·后端
Evand J8 小时前
【PSINS工具箱】MATLAB例程,二维平面上的组合导航,EKF融合速度、位置和IMU数据,4维观测量
开发语言·matlab·平面
2025年一定要上岸8 小时前
【数据结构】-4-顺序表(上)
java·开发语言·数据结构
浩瀚蓝天dep19 小时前
使用Ollama部署自己的本地模型
ai大模型·ollama·deepseek