目錄
if elseif else
switch case otherwise
while
exercise練習
for
預宣告
練習題
break
tips編程的小技巧
functions函數
練習題
函數句柄
if elseif else
如果condition為真,執行語句
if condition1statement1
elseif condition2statement2
elsestatement3
end
實際例子:
a = 5;
if rem(a,2) == 0%余數remainderdisp('a is even')%偶數
elsedisp('a is odd')%奇數
end
運行結果:a is odd
switch case otherwise
用switch語句內容判斷執行:
switch expressioncase value1statement1case value2statement2otherwisestatement
end
實際例子:
input_num = 10;
switch input_numcase -1disp('negative 1')case 0disp('zero')case 1disp('positive 1')otherwisedisp('other value')
end
運行結果與input_num有關,例如這個結果為:other value
while
標準:
while expressionstatement
end
舉例:
n = 1;
while prod(1:n)<1e100%prod數組的乘積 1e100是1*10的100次方n = n+1;
end
運行結果:計算1累乘到小于10的100次方有多少個數--n=70
exercise練習
%use while loop to calculate the summation of the series 1+2+3...+999
m = 1;summation = 0;while m <1000summation = summation + m;m = m + 1;endsummation
運行結果:
for
標準:
for variable=start:increment:endcommand
例子:
for n = 1:2:10a(n)=2^n;
end
disp(a(1:2:10))
結果:
預宣告
pre-allocating space to variables
能夠極大程度縮短代碼運行時間
例如:
tic
for ii = 1:2000for jj = 1:2000A(ii,jj) = ii+jj;end
end
toctic
A = zeros(2000,2000);
for ii = 1:size(A,1)for jj = 1:size(A,2)A(ii,jj) = ii+jj;end
end
toc
結果發現,時間差距還是很大,所以預宣告還是很重要的:
練習題
A = [0 -1 4;9 -14 25;-34 49 64];
B = A;
for i = 1:size(B,1)for j = 1:size(B,2)if B(i,j)<0B(i,j) = -B(i,j);endend
end
B
運行結果(這玩意太簡單了):
break
就是跳出循環,跟c/c++或者python邏輯same
x = 2;k = 0;error = inf;
error_threshold = 1e-32;
while error > error_thresholdif k>100breakendx = x-sin(x)/cos(x);error = abs(x - pi);k = k + 1;
end
tips編程的小技巧
- 在腳本開頭,使用
clear all
清除之前的變量,用close all
關閉所有圖形窗口。 - 在命令末尾使用分號
;
,以抑制不必要的輸出。 - 使用省略號
...
使腳本更具可讀性,比如示例中對矩陣A
的分行定義。 - 若要在腳本結束前終止它,可按下
Ctrl + C
functions函數
例如自由落體的代碼x=x0+v0t+1/2gt^2的函數:
function x = freebody(x0,v0,t)
x = x0+v0.*t+1/2*9.8*t.*t;
(在matlab中也是.m文件
例如2 計算牛頓第二定律(沒記錯的話)F=ma:
function [a F] = acc(v2,v1,t2,t1,m)
a = (v2-v1)./(t2-t1);
F = m.*a;
練習題
就是輸入一個華攝氏度,輸入攝氏度,而且什么時候按回車什么時候停止:
我的代碼:(注意一點:一定要把輸入的字符F轉化為double,我說怎么一直不對 用str2double)
%輸入華攝氏度 輸出攝氏度
function F2C()%fahrenheit to centigrade
F = input('請輸入華攝氏度值:','s');
out0 = ['華攝氏度為:',num2str(F)];
disp(out0)
a = isempty(F);
while(a==0)C = (str2double(F)-32)/1.8;out = ['攝氏度是:',num2str(C)];disp(out)F = input('請輸入華攝氏度的值:','s');out0 = ['華攝氏度為:',num2str(F)];disp(out0)a = isempty(F);
end
disp('input is end')
運行結果:
函數句柄
就是不用寫.m文件直接在當前文檔中寫一個函數(我感覺有點亂,除非很簡單的函數方便
%% function handle函數句柄
f = @(x) exp(-2*x);
x = 0:0.1:2;
plot(x,f(x))