最近跟着B站上的MATLAB教程系列-台大(共14课)学习MATLAB基础。视频中有一些小练习,在此做个记录。如果也有其他学习此视频课程的同学看到了我的小代码们,欢迎贴出更好的方法~
第三课中的练习,温度转换。要求,除非输入的不是数字,程序停止,否则一直提示输入温度。
function y = FtoC (F)
tips1 = 'Temperature in F is: ';
F = input (tips1);
while ( (isnumeric(F) == 1) ) && (isempty(F) == 0)
% || (isempty(str2num(F)) == 0)
% 第五行这一方法可以用于判断输入是否为字符,但此程序中没有必要一定加这个条件
C = (F-32) .* (5/9);
disp(['Temperature in C is: ',num2str(C)]);
tips1 = 'Temperature in F is: ';
F = input (tips1);
end
输出结果:
1.
>>FtoC
Temperature in F is: 32
Temperature in C is: 0
Temperature in F is: 45
Temperature in C is: 7.2222
Temperature in F is: 12
Temperature in C is: -11.1111
Temperature in F is:
2. If we continue to input a character:
Temperature in F is: 'k'
>>
(the program stops)
3. Input the space or press 'enter'
>> FtoC
Temperature in F is:
>>
(the program stops)
附上对str2num(F)的使用说明:
如果F为一个字符,则:
>> str2num('k')
ans =
[]
>> str2num('abc')
ans =
[]
可以看到,如果输入为字符,则返回一个空矩阵,因此可以通过这种方法来判断输入是否为字符。
>> isempty(str2num('abc'))
ans =
logical
1