MATLAB課堂作業: 作業五
1. Create a 3X3X2 matrix A which contains a matrix of magic(3) and another rand(3,3)*10.
ANS:
>> A(:,:,1)=magic(3); % 第一頁為magic(3)矩陣
>> A(:,:,2)=rand(3,3)*10 % 第二頁為rand(3,3)*10矩陣
A(:,:,1) =
8 1 6
3 5 7
4 9 2
A(:,:,2) =
4.4470 9.2181 4.0571
6.1543 7.3821 9.3547
7.9194 1.7627 9.1690
2. Assume that matrices A=[45 89 99; 12 34 55], B=[15 25 45; 65 50 30]. Find matrices that join A & B both in vertical and horizontal directions. Also, find a two-page matrix with A & B stored in separate pages. Use commands horizcat and verticat to check the results with those from above.
ANS:
利用cat指令將兩矩陣合併
>> A=[45 89 99; 12 34 55];
>> B=[15 25 45; 65 50 30];
>> Cvertical=cat(1,A,B) % dim=1時,表示將A、B矩陣垂直疊加
Cvertical =
45 89 99
12 34 55
15 25 45
65 50 30
>> C1=[A;B]
C1 =
45 89 99
12 34 55
15 25 45
65 50 30
兩者結果相同
>> Chorrizontal=cat(2,A,B) % dim=2時,表示將A、B矩陣水平疊加
Chorrizontal =
45 89 99 15 25 45
12 34 55 65 50 30
>> C2=[A,B]
C2 =
45 89 99 15 25 45
12 34 55 65 50 30
兩者結果相同
>> Cpage=cat(3,A,B) % dim=3時,表示將A、B矩陣以分置於不同頁方式疊加
Cpage(:,:,1) =
45 89 99
12 34 55
Cpage(:,:,2) =
15 25 45
65 50 30
3. Find a matrix M which contains A as the first and third pages and B the second and fourth pages.
ANS:
>> A=[45 89 99; 12 34 55];
>> B=[15 25 45; 65 50 30];
>> M=cat(3,A,B,A,B)
M(:,:,1) =
45 89 99
12 34 55
M(:,:,2) =
15 25 45
65 50 30
M(:,:,3) =
45 89 99
12 34 55
M(:,:,4) =
15 25 45
65 50 30
4. Construct a 2X2 cell array that contains 'Eric' [90 100]; 'Peter' [35 60]; 'Jan' [77 67].
ANS:
>> D=cell(3,2);
>> D={'Eric' [90 100]; 'Peter' [35 60]; 'Jan' [77 67]}
D =
'Eric' [1x2 double]
'Peter' [1x2 double]
'Jan' [1x2 double]
5. Construct a structural Array that contains the following data:
Name: 'Philip', 'Peter','Roberts', 'Roe'
Age: 35, 45, 55, 60
Salary: 50,000 40,000 80,000 120,000
ANS:
>> Database(1).Name='Philip';Database(1).Age=35;Database(1).Salary=50000;
>> Database(2).Name='Peter';Database(2).Age=45;Database(2).Salary=40000;
>> Database(3).Name='Roberts';Database(3).Age=55;Database(3).Salary=80000;
>> Database(4).Name='Roe';Database(4).Age=60;Database(4).Salary=120000;
>> Database % 顯示整個結構性矩陣
Database =
1x4 struct array with fields:
Name
Age
Salary
亦可顯示結構性矩陣內各筆資料內容
>> Database(1) % 第一筆
ans =
Name: 'Philip'
Age: 35
Salary: 50000
>> Database(2) % 第二筆
ans =
Name: 'Peter'
Age: 45
Salary: 40000
>> Database(3) % 第三筆
ans =
Name: 'Roberts'
Age: 55
Salary: 80000
>> Database(4) % 第四筆
ans =
Name: 'Roe'
Age: 60
Salary: 120000
另外,以struct指令亦可得到相同的結果
>>Database2=struct('Name',{'Philip','Peter','Roberts','Roe'},'Age',{35,45,55,60},'Salary',{50000,40000,80000,120000})
Database2 =
1x4 struct array with fields:
Name
Age
Salary
>> Database2(1)
ans =
Name: 'Philip'
Age: 35
Salary: 50000
>> Database2(2)
ans =
Name: 'Peter'
Age: 45
Salary: 40000
>> Database2(3)
ans =
Name: 'Roberts'
Age: 55
Salary: 80000
>> Database2(4)
ans =
Name: 'Roe'
Age: 60
Salary: 120000
沒有留言:
張貼留言