1. 程式人生 > 其它 >MatLab---矩陣乘法與變數的顯示與輸出

MatLab---矩陣乘法與變數的顯示與輸出

一、矩陣的乘法

M1=randi([1,3],[3,4])

M1 =

3 1 1 2
3 1 3 1
1 2 1 3

M2=randi([1,9],[4,3])

M2 =

4 8 8
9 3 6
1 9 8
6 7 3

M1*M2

ans =

34 50 44
30 61 57
41 44 37

矩陣的乘法:第一個矩陣的列數與第二個矩陣的行數必須相同

M0=randi([1,9],[4,4])

M0 =

3 3 9 3
3 4 2 5
6 8 8 4
8 6 7 6

>> M0*M0

ans =

96 111 126 78
73 71 86 67
122 138 162 114
132 140 182 118

>>
>> M0^2

ans =

96 111 126 78
73 71 86 67
122 138 162 114
132 140 182 118

>> M0.^2 

ans =

9 9 81 9
9 16 4 25
36 64 64 16
64 36 49 36

M0*M0=M0^2 結果是一致的;

而M0.^2是每個位置元素的平方

二、矩陣的內積

v1=randi([1,9],[1,3])

v1 =

4 4 6

>> v2=randi([1,9],[1,3])

v2 =

7 7 7

sum(v1.*v2)

ans =

98

也可以用轉置來實現

v1*v2'   轉置的優先順序高於矩陣乘法的優先順序

ans =

98

三、矩陣的叉乘

cross(v1,v2)

ans =

-14 14 0

>> v1=[1 2 3 4]

v1 =

1 2 3 4

>> cross(v1,v1)
錯誤使用 cross
在獲取交叉乘積的維度中,A 和 B 的長度必須為 3

四、特殊矩陣

1.生成希爾伯特矩陣

hilb(3)

ans =

1.0000 0.5000 0.3333
0.5000 0.3333 0.2500
0.3333 0.2500 0.2000

2.生成帕斯卡矩陣,由楊輝三角形表組成的矩陣稱為帕斯卡矩陣

pascal(5)

ans =

1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70

3.生成幻方,N階矩陣。它的行、列、對角線之和相同。

magic(4)

ans =

16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1

五、ind2sub() 將矩陣的線性下標轉換成幾行幾列

M=randi([1,9],[4,4])

M =

8 5 5 2
2 8 4 3
6 2 8 7
3 3 9 4

[I,J]=ind2sub(size(M),find(M==2))

I =

2
3
1


J =

1
2
4

六、變數的顯示與輸出

建立指令碼檔案

1.有兩種輸出,分別是disp與fprintf

radius=5;
area1=pi*radius^2;
disp(['the area of the disc is ' num2str(area1)]);

以上的情況要用到一個函式num2str()將數字轉換成字元的形式才可以與前面的捏合在一起


fprintf('the area of the disc is %f \n',area1); % %f以浮點數的形式表示出來;
fprintf('the area of the disc is %d \n',area1); % %d以科學計數法的形式表示出來
fprintf('the area of the disc is %6.2f \n',area1); %佔位符 佔6個位置,小數點後2位
fprintf('the area of the disc is %+6.2f \n',area1); %佔位符 佔6個位置,小數點後2 有加號,便於有正有負時,可以對齊

2.num2str()

num2str(pi,8)

ans =

'3.1415927'

>> num2str(pi,'%8.2f')

ans =

'3.14'

>> num2str(pi)

ans =

'3.1416'

七、矩陣的正除號與反除號

A=eye(3)

A =

1 0 0
0 1 0
0 0 1

>> A=eye(3/3)

A =

1

>> A=eye(3)/3

A =

0.3333 0 0
0 0.3333 0
0 0 0.3333

>> B=eye(3)*3

B =

3 0 0
0 3 0
0 0 3

>> A\B

ans =

9 0 0
0 9 0
0 0 9

>> A\B%A的逆 乘以 B

ans =

9 0 0
0 9 0
0 0 9

>> A/B %A 乘以 B的逆

ans =

0.1111 0 0
0 0.1111 0
0 0 0.1111

>> %誰在下面,誰是逆