%%%%%create a Matrix%%%%%
disp('create a Matrix');
%separate the elements with either a comma(,)or a space
%separate the rows with semicolons(;)
a = [1,2,3;4,5,6;7,8,10]
%another way to creat a matrix is to use a function
%such as ones(),zeros(),or rand()
b=zeros(2,5)
%create an equally spaced vector of values using the more general form start:step:end
c=0:10:100
%%%%%Matrix Operation%%%%%
disp('Matrix Operation');
%+,',inv(),*,.*,.^
%to transpose a matrix,use a single quote(')
a1=a'
%to inverse a matrix,use a function,inv()
a2=inv(a)
%element-wise multiplication(点乘).*
a3=a.*a
%raise each element of a to the third power
a4=a.^3
%%%%%Concatenation%%%%%
disp('Concatenation');
a5=[a,a]
a6=[a;a]
%%%%%array indexing%%%%%
disp('array indexing');
%there are two ways to refer to a particular element in an array
%specify row and column subscripts
c1=a(2,3)
%use a single subscript that traverses down each column in order
%如这儿a是一个3*3的矩阵,对于a(7),将按顺序从第一列开始挨着挨着数7个,此处为1,4,7,2,5,8,3,则a(7)=3
c2=a(7)
%refer to multiple elements of an array,use the colon(:) to specify a range of the form start:end
%此处取a矩阵的1、2行及2列
c3=a(1:2,2)
运行结果:
(程序语句后加分号时,运行结果在命令窗口不显示;不加时,运行结果会在命令窗口显示;此处为了显示结果,均未加分号)
>> test_arrays
create a Matrix
a =
1 2 3
4 5 6
7 8 10
b =
0 0 0 0 0
0 0 0 0 0
c =
0 10 20 30 40 50 60 70 80 90 100
Matrix Operation
a1 =
1 4 7
2 5 8
3 6 10
a2 =
-0.6667 -1.3333 1.0000
-0.6667 3.6667 -2.0000
1.0000 -2.0000 1.0000
a3 =
1 4 9
16 25 36
49 64 100
a4 =
1 8 27
64 125 216
343 512 1000
Concatenation
a5 =
1 2 3 1 2 3
4 5 6 4 5 6
7 8 10 7 8 10
a6 =
1 2 3
4 5 6
7 8 10
1 2 3
4 5 6
7 8 10
array indexing
c1 =
6
c2 =
3
c3 =
2
5
>>
tips:
To clear all the variables from the workspace,use the clear command
To open the function documentation in a separate window ,use the doc command
eg:doc zeros
To clear command window,use the clc command