跳轉到內容

MATLAB 程式設計/MATLAB 命令示例

來自華夏公益教科書


MATLAB 的有趣之處在於它是動態編譯的。換句話說,當你使用它時,你不會將所有程式碼都透過編譯器執行,生成可執行檔案,然後執行可執行檔案來獲得結果。相反,MATLAB 只需逐行執行計算,而無需可執行檔案。

部分原因是,可以使用與檔案中使用的相同語法,在命令列逐行進行計算。如果你願意,甚至可以在命令列編寫迴圈和分支。當然,這通常會導致大量浪費的努力,因此,除了非常簡單的計算、測試某個函式、語法等是否有效或呼叫你放入 .m 檔案中的函式之外,其他任何操作都應該在 .m 檔案中完成。

MATLAB 可以從命令列執行簡單計算器的功能。我們透過現實生活中的一些常見數學問題進行講解。

以下是一些在 MATLAB 中求解的數學問題示例

油漆覆蓋率

[編輯 | 編輯原始碼]
A home painter at work

一名房屋油漆工通常使用 10 升白色油漆來覆蓋平均 120 平方米的單層塗層。

計算一名房屋油漆工需要購買多少 10 升油漆罐來粉刷一個房間,房間尺寸為 13 米 x 9 米,從地板到天花板的高度為 5 米。

房間裡還有兩個窗戶,尺寸為 1.5 米 x 0.75 米和 2 米 x 1.25 米,以及一個門,尺寸為 1.2 米 x 3 米。

>> room_area=13*9*5 %calculating the overall area of wall for the room

room_area =
   585
   
>> window_area=(1.*0.75)+(2*1.25)

window_area =
    3.2500

>> door_area=1.2*3

door_area =
    3.6000
    
>> paint_area=room_area-window_area-door_area

paint_area =
  578.1500

>>%amount of paint can needed 
paint_area / 120

ans =
    4.8179 
%house painter needed equaivalent of 5 tin cans to paint the room

地球到太陽的距離

[編輯 | 編輯原始碼]
Naturalis Biodiversity Center - Museum - Exhibition Earth 03 - Sun-Earth model, tilt earth, seasons

從太陽到地球的距離相當於 1.5 億公里(150,000,000 公里)。

如果人類發射了一枚能夠達到 7 公里/秒(忽略所有空氣摩擦、重力拉力)恆定速度的先進火箭,那麼火箭從地球到太陽需要多少年?

>> distance = 150000000

distance =
   150000000

>> speed = 7

speed =
     7
     
>> time = distance / speed

time =
   2.1429e+07

>> time_to_reach_sun=time/(3600*24*365) % 3600= 1 hour =3600secs, 1 day = 24hour, 1 year=365days(discounting leap years)

time_to_reach_sun =
    0.6795

桌面遊戲的骰子滾動

[編輯 | 編輯原始碼]
Double-six-dice

你邀請一些朋友來玩桌面遊戲,但不知何故,應該附帶遊戲的骰子不見了。建立一個 MATLAB 程式來擲兩個骰子(有 6 個面)。

你需要使用 randi 命令來生成隨機數。可以在這裡學習更多命令:MATLAB 程式設計/MATLAB 基礎/MATLAB 運算子

>> diceroll = randi(6) + randi(6) % press up button to recall last command and press Enter

diceroll =
     9

>> diceroll = randi(6) + randi(6)

diceroll =
     6

>> diceroll = randi(6) + randi(6)

diceroll =
     9

>> diceroll = randi(6) + randi(6)

diceroll =
    11

>> diceroll = randi(6) + randi(6)

diceroll =
     5

>> diceroll = randi(6) + randi(6)

diceroll =
    12

外部資源

[編輯 | 編輯原始碼]

ControlTheoryPro.com

華夏公益教科書