Find exact pattern in string

3 vues (au cours des 30 derniers jours)
Jasmien Sihota
Jasmien Sihota le 18 Fév 2021
I am trying to find the exact pattern in my array including the number of characters.
clear all; close all;
code = ...
[".----";"..---";"...--";"....-";".....";"-....";"--...";"---..";"----.";...
"-----";".-";"-...";"-.-.";"-..";".";"..-.";"--.";"....";"..";".---";...
"-.-";".-..";"--";"-.";"---";".--.";"--.-";".-.";"...";"-";...
"..-";"...-";".--";"-..-";"-.--";"--..";"..--.-"];
letter = ...
["1";"2";"3";"4";"5";"6";"7";"8";"9";"0";"A";"B";"C";"D";"E";"F";"G";"H";...
"I";"J";"K";"L";"M";"N";"O";"P";"Q";"R";"S";"T";"U";"V";"W";"X";"Y";"Z";"-"];
userInput = input("Enter your morse code ", 's');
numcharacters = count(userInput, "/")
for i = 1:length(numcharacters)
if ismember (userInput(i), code)
k = strmatch(code,userInput(i), 'exact')
message = letter(k)
else
disp('error')
end
end
This version of the code outputs an empty array for k
When I change it to
k = matches(code,userInput(i))
it only matches to "T" or "E". I need to match the whole pattern for my code.

Réponse acceptée

Walter Roberson
Walter Roberson le 18 Fév 2021
Your code is expecting userInput(i) to be an entire group of pulses. But it is not. userInput is a character vector and (i) is indexing individual characters.
You have three choices:
1. remove the 's' option from input() and require that the user enter in the form
["..-","-"]
with your program crashing if they make a mistake; or
1b) same but put in a try/catch to handle the inevitable errors more smoothly; or
2. Leave in the 's' but expect the user to use the above form but scan the character vector to ensure that it has the right format, and use eval() on the validated character vector;
3. Leave in the 's' and continue to expect the user to use / to mark the end of blocks, and split the character vector into pieces at each / and string() the cell array of character vectors you got from the splitting to create the string array that you can use (i) indexing with.

Plus de réponses (0)

Produits


Version

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by