1.MATLAB通过%对代码进行注释,使用两个%%可以对代码进行分块,
运行的时候选择run section(运行节)按钮来运行区块里面的代码,
选择run(运行)按钮,运行整个程序的代码
2.MATLAB程序结构
if,elseif,else
for
switch,case
otherwise
try,catch
while
break
continue
end
pause
return
3.MATLAB关系运算符/逻辑运算符
< 小于 Less than
<= 小于等于 Less than or equal to
> 大于 Greater than
>= 大于等于 Greater than or equal to
== 等于等于 Equal to
~= 不等于 Not equal to
&& 逻辑与 And
|| 逻辑或 Or
4.if语句的结构
if condition1
statement1
elseif condition2
statement2
else
statement3
end
elseif和else是可选的,不一定要有
5.switch语句的结构
switch expression
case value1
statement1
case value2
statement2
.
.
.
otherwise
statement
end
6.while循环的结构
while expression
statement
end
7.for循环的结构
for variable=start:increment:end
commands
end
8.crtl+c可以终止程序的执行
贴上自己写的练习题答案
Exercise 1:
题目:
• Use structured programming to:
1. Find the entries in matrix 𝐠that are negative
2. Store these entries’ position in a matrix B
3. Change the values of these entries to zero
0 -1 4
A = 9 -14 25
-34 49 64
代码:
clear
clc
A = [0 -1 4;9 -14 25;-34 49 64];
B = zeros(size(A,1), size(A,2));
for ii = 1:size(A, 1)
for jj = 1:size(A, 2)
B(ii, jj) = A(ii, jj);
end
end
disp(A);
disp(B);
for mm = 1:size(B, 1)
for nn = 1:size(B, 2)
if B(mm, nn) < 0
B(mm, nn) = -B(mm, nn);
end
end
end
disp(B);
Exercise 2:
题目:
• Write a function that asks for a temperature in
degrees Fahrenheit
• Compute the equivalent temperature in degrees
Celsius
• Show the converted temperature in degrees
Celsius
• The script should keep running until no number is
provided to convert
• You may want to use these functions:
input, isempty, break, disp, num2str
代码:
function y = F2C(~)
prompt = 'Temperature in F. ';
x = input(prompt);
while 1
if isempty(x) == 0 % 如果x是非空的执行以下代码,注意x可能是一个array或者matrix
y = (x-32).*(5/9);
% 有以下三种输出方式
% 方式1
str = ['==> Temperature in C = ',num2str(y)];
disp(str)
% 方式2 和c的格式化输出很像哦
str2 = sprintf('==> Temperature in C = %0.4f', y);
disp(str2)
% 方式三
fprintf('==> Temperature in C = %0.4f \n', y);
prompt = 'Temperature in F. ';
x = input(prompt);
elseif isempty(x) == 1 % 说明x是空的
break; % 跳出while循环
end
end