Introduction to Matlab
Matrix laboratory (matrix&laboratory)
R2022a: version in the first half of 2022
R2022b: version in the second half of 2022
Matlab interface
The command line window
interacts directly with the user, which is equivalent to a calculator
>> 1+1
ans =
2
>> 5-2
ans =
3
>> 2*2
ans =
4
>> 3/4
ans =
0.7500
clc: Clear the command line window
Editor:
The red box in the figure below is the current program name.
If there is an * in the upper right corner of the program name, it means that the program has unsaved content. (Ctrl+S to save)
·Variable naming rules (the title is the same)
Variable names are case-sensitive
Variable names are concise and clear, try to be as clear as possible
All variables that have stored values will be displayed in the work area.
It must start with a letter, but numbers and underscores can be added after it, and punctuation cannot be added.
The length of the variable name does not exceed 63 characters (does anyone really have such a long name)
Comments in Matlab
% Common comments
%% Comments that occupy a single line ( There are upper and lower horizontal lines to separate)
clear Clear all variables in Workspace (right workspace)
clc Clear all commands in Command Window (command line window)
Data type
% character/string
>> str='Hello World!'
str =
‘Hello World!’
>> str
str =
‘Hello World!’
%字符串长度
>> length(str)
ans =
12
matrix:
>> A=[1 2 3;4 5 6;7 8 9]
A =
1 2 3
4 5 6
7 8 9
>> A=[1,2,3;4,5,6;7,8,9]
A =
1 2 3
4 5 6
7 8 9
%矩阵转置
>> B=A'
B =
1 4 7
2 5 8
3 6 9
%
>> C=A(:)
C =
1
4
7
2
5
8
3
6
9
%生成全是0的矩阵
>> D=zeros(512,512);
%生成随机数
%rand(m,n)生成m行n列的均匀分布的伪随机数(0-1之间)
>> D=rand(512,512);
%randn生成标准正态分布的伪随机数(均值为0,方差为1)
%randi(iMax)在开区间(0,iMax)生成均匀分布的伪随机数
%randi(iMax,m,n)在开区间(0,iMax)生成mXn型随机矩阵
%r = randi([iMin,iMax],m,n)在开区间(iMin,iMax)生成mXn型随机矩阵
· Matrix subscript
A = magic(5)
B = A(2,3)
C = A(3,:) % :为取全部,那么这条语句表示取第三行
D = A(:,4) %取第四列
[m,n] = find(A > 20) %找到大于20的序号值/矩阵
%取的是索引值
3. Matlab common functions
>> sqrt(25)
ans =
5
>> abs(-5)
ans =
5
>> round(3.1415)
ans =
3
>> floor(3.9)
ans =
3
>> round(3.9)
ans =
4
Three major program structures (sequence/selection/loop)
Order:
Select:
clc;
clear;
x=input('请输入您的年龄:');
if x > 18
fprintf('您的年龄为%d,您已经成年。',x);
else
fprintf('您的年龄为%d,您还未成年。',x);
End
cycle:
%1到100的和
sum=0;
for i=1:100
sum=sum+i;
end
fprintf('1到100的和为%d',sum);
%99乘法表
for i=1:9
for j=1:9
fprintf('%dx%d=%d\t',i,j,i*j);
end
fprintf('\n');
end