-2 matlab
function [output] = english2morse(text)
% Where a = 1, b = 2, c = 3 ... space numberals start here... 0 - 9 specials characters start here: in this order| begining . , ? ! : " ' = end
definitions = {' .-' ' -...' ' -.-.' ' -..' ' .' ' ..-.' ' --.' ' ....' ' ..' ' .---' ' -.-' ' .-..' ' --' ' -.' ' ---' ' .--.' ' --.-' ' .-.' ' ...' ' -' ' ..-' ' ..-' ' .--' ' -..-' ' -.--' ' --..' ' ' '-----' '.----' '..---' '...--' '....-' '.....' '-....' '--...' '---..' '----.' '.-.-.-' '--..--' '..--..' '..--.' '---...' '.-..-.' '.----.' '-...-'};
output = definitions(text);
end
clc
clear
i = 1;
% Asks user for txt, and checks to see if the input is valid, ifnot, get
% new user input, else break while loop and continue program exectution.
while i == 1
disp('Program converts strings to morce code. ONLY ACCEPTS: A-Z a-z 0-9 , . , ? ! : " `')
pause(1)
text = input('Enter a string: ', 's');
text = lower(text)
disp('Checking to see if correct values entered.')
converted = zeros(1, length(text))
for x = 1:length(text)
% for lowercase
if text(x) >= 97 && text(x) <= 122
% for numberals 0-9
converted(x) = double(text(x) - 96);
i = 0;
elseif text(x) >= 48 && text(x) <= 57
converted(x) = text(x) - 20
i = 0;
% for special characters, listed above
elseif text(x) == 46 || text(x) == 44 || text(x) == 63 || text(x) == 33 || text(x) == 58 || text(x) == 34 || text(x) == 39 || text(x) == 61
switch text(x) == 46 || text(x) == 44 || text(x) == 63 || text(x) == 33 || text(x) == 58 || text(x) == 34 || text(x) == 39 || text(x) == 61
case text(x) == 46
converted(x) = text(x) - 8
case text(x) == 44
converted(x) = text(x) - 5
case text(x) == 63
converted(x) = text(x) - 23
case text(x) == 33
converted(x) = text(x) + 8
case text(x) == 58
converted(x) = text(x) - 16
case text(x) == 34
converted(x) = text(x) + 9
case text(x) == 39
converted(x) = text(x) +5
case text(x) == 61
converted(x) = text(x) - 16
end
i = 0;
else
i = 1;
end
end
end
disp(converted)
disp(english2morse(converted))
Run Code Online (Sandbox Code Playgroud)
小智 5
请从脚本中删除以下部分,并将其保存在名为的文件中english2morse.m:
function [output] = english2morse(text)
% Where a = 1, b = 2, c = 3 ... space numberals start here... 0 - 9 specials characters start here: in this order| begining . , ? ! : " ' = end
definitions = {' .-' ' -...' ' -.-.' ' -..' ' .' ' ..-.' ' --.' ' ....' ' ..' ' .---' ' -.-' ' .-..' ' --' ' -.' ' ---' ' .--.' ' --.-' ' .-.' ' ...' ' -' ' ..-' ' ..-' ' .--' ' -..-' ' -.--' ' --..' ' ' '-----' '.----' '..---' '...--' '....-' '.....' '-....' '--...' '---..' '----.' '.-.-.-' '--..--' '..--..' '..--.' '---...' '.-..-.' '.----.' '-...-'};
output = definitions(text);
end
Run Code Online (Sandbox Code Playgroud)
删除后保存脚本,编辑后保存该功能,再次运行脚本.
说明: MATLAB在函数和脚本之间有所不同.
一个MATLAB代码文件,其中第一个非注释关键字是function(出乎意料!)一个函数,即通常等待某些输入的一段代码,根据它返回一些输出,并在它们之间做一些事情.每次调用函数时,所有输入,输出和临时数据都在其自己的函数工作空间中创建.
不接受最终注释的文件(不是以function(或classdef)开头)是一个脚本,旨在立即执行,使用全局工作空间中可用的任何数据,并将其输出存储在同一个全局工作空间中.
现在,MATLAB不希望将函数定义与脚本混合使用.这就是为什么函数应该在它自己的文件中,并且脚本在它自己的文件中.