A = [1,2,3,4,5,6,5,4,6] A = [123; 452; 327] B = 1:2:9%第二个参数为步长,不可缺省 B = 1:3:9 C = repmat(B,3,2) %重复执行3行2列 D = ones(2,4) %生成一个2行4列的全1矩阵 E = zeros(2,4)%生成一个2行4列的全0矩阵
四则运算
1 2 3 4 5 6 7 8
A = [1234; 5678] B = [1122; 2211] C = A + B D = A - B E = A * B' F = A .* B % .*表示对应项相乘 G = A / B %相当于A*B的逆 G*B = A G*B*pinv(B) = A*pinv(B) G = A*pinv(B),相当于A乘B H = A ./ B % ./表示对应项相除
矩阵下标
1 2 3 4 5 6
A = magic(5) B = A(2,3) C = A(3,:) % :为取全部,那么这条语句表示取第三行 D = A(:,4) %取第四列 [m,n] = find(A > 20) %找到大于20的序号值/矩阵 %取的是索引值
控制流
if……else……end
1 2 3 4 5 6 7 8 9
a = randi(100, 1);
if a < 30 disp('small') elseif a < 80 disp('medium') else disp('large') end
switch dayString case'Monday' disp('Start of the work week') case'Tuesday' disp('Day 2') case'Wednesday' disp('Day 3') case'Thursday' disp('Day 4') case'Friday' disp('Last day of the work week') otherwise disp('Weekend!') end
for
1 2 3
for n = 3:32 r(n) = rank(magic(n)); end
while(注意:break,continue,return)
1 2 3 4 5 6 7 8 9 10 11 12
a = 0; fa = -Inf; b = 3; fb = Inf; while b-a > eps*b x = (a+b)/2; fx = x^3-2*x-5; ifsign(fx) == sign(fa) a = x; fa = fx; else b = x; fb = fx; end end x