matlab基础编程学习
一、matlab简介
1.是一款强大的数值计算软件,基于矩阵运算,可以处理大量高精度数据,且具有较高运行效率。
(超级建议大家去学)
2.快捷键介绍:
注释:ctrl+R
取消注释:ctrl+T
运行节:%%(加空格) 可以运行某一节代码
整理缩进:ctrl+I
取消改动:ctrl+Z
运行程序:F5
单步执行:F10
设置断点:F12
二、入门操作
1.变量命名: 只能以字母开头(C语言还可以以下划线开头),且最多不超过19个字符 。
文件命名:用英文字符,首字符不能是数字或下划线
2.控制结构:
2.1循环结构:
/****for循环****/
for n = 1:10 //表示i从1到10逐次+1,循环十次
x(n) = sin(n*10);
end //终止for循环
/****while循环****/
x = 0;
sum = 0;
while x < 101
sum = sum + x;
x = x + 2;
end
2.2选择结构
/****if-else语句*****/
if x > 1
f = x^2 + 1;
else if x <= 0
f = x^3;
else
f = 2 * x
end
/*****switch语句******/
num = input('请输入一个数');
switch num
case -1 //注意case后面没有冒号
disp('I am a teacher.');
case 0
disp('I am a student.');
case 1
disp('You are a teacher.');
otherwise //等同于C语言中的 default
disp('You are a student.');
end
3.定义函数
function [outarg1,outarg2] = haha(inputarg1,inputarg2)
%**关键字***因变量**因变量****=*函数名**自变量****自变量****
%加注释
outarg1 = inputarg1 ;
outarg2 = inputarg2 ;
%函数结束
end
4.定义类
%类定义***类名
classdef hehehe
%属性
properties
property1
end
%方法
methods
function [outarg1,outarg2] = haha(inputarg1,inputarg2)
%**关键字***因变量**因变量****=*函数名**自变量****自变量****
%加注释
outarg1 = inputarg1 ;
outarg2 = inputarg2 ;
%函数结束
end
end
%类结束
end
三、基本运算和函数
1.预定义的变量
变量 | 含义 |
---|---|
ans | 预设结果变量名 |
eps | 正数极小值 |
pi | π值 |
inf | 无穷大 |
NaN | 无法定义 0/0 |
虚数单位 |
2.符号
2.1运算符号
符号 | 解释 |
---|---|
+ | 适用于两个数或者同阶矩阵相加 |
- | 适用于两个数或者同阶矩阵相减 |
* | 适用于两个数或者符合x y* y z 矩阵相乘 |
.* | 点乘,矩阵预算 |
/ | 适用于两个数或者符合规则的矩阵相除 |
./ | 点除,矩阵预算 |
^ | 乘幂 |
.^ | 点乘幂,矩阵预算 |
\ | 左除 |
" . "的影响:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VB4QcoS2-1666549148142)(C:\Users\zxru\AppData\Roaming\Typora\typora-user-images\1666547624379.png)]
2.2符号变量的声明
在命令行中随便输入一个a = 10,表明a是一个常数变量,而一般在求导和积分时,几乎都是用 符号进行运算
x=sym(‘x’) —— 表明x是符号变量
syms x y z —— 定义多个符号变量
syms f(x) —— 定义两个符号变量,f和x,且二者之间还有函数关系
在声明符号函数时,还可以使用inline函数:
f = inline(“x^3+5*x”) 或者 ff = inline(‘-x*sin(x^2-x-1)’, ‘x’) 如果不带引号,则其内部的变量都应已知。
3.输入输出函数
%输入函数
input("hello")
%输出函数
disp("I am here")
4.常用函数总结
5.逻辑运算
5.1 等于 和 不等
== 等于 ~=不等于
5.2 逻辑运算
5.3相关函数
四、绘图
4.1plot函数
%x,y是向量,横纵坐标 ‘线型和颜色’
plot(x,y,'r o')
%常用颜色 y m r g b w k
%常用线型 . o x + * - : -. --
4.2 符号函数
4.3图像处理
%格栅
grid on
gred off
%x y 轴标记
xlabel("")
ylabel("")
%标题
title("")
%随鼠标定位
gtext("")
%定制坐标
axis([xmin,xmax,ymin,ymax])
%保持
hold on
%释放
hold off
%窗口
figure()
%分割窗口
subplot(row,col,1)
4.4三维图像
plot3(f(x),f(y),f(z),'')
可以参考:https://ww2.mathworks.cn/products/matlab/plot-gallery.html
s([xmin,xmax,ymin,ymax])
%保持
hold on
%释放
hold off
%窗口
figure()
%分割窗口
subplot(row,col,1)
4.4三维图像
plot3(f(x),f(y),f(z),‘’)
可以参考:https://ww2.mathworks.cn/products/matlab/plot-gallery.html