我想在MATLAB中编写一个代码,将一个字母转换为NATO字母表。例如“&strong> hello '将被重写为 Hotel-Echo-Lima-Lima-Oscar 。我在代码方面遇到了一些麻烦。到目前为止,我有以下内容:
function natoText = textToNato(plaintext)
plaintext = lower(plaintext);
r = zeros(1, length(plaintext))
%Define my NATO alphabet
natalph = ["Alpha","Bravo","Charlie","Delta","Echo","Foxtrot","Golf", ...
"Hotel","India","Juliet","Kilo","Lima","Mike","November","Oscar", ...
"Papa","Quebec","Romeo","Sierra","Tango","Uniform","Victor",...
"Whiskey","Xray","Yankee","Zulu"];
%Define the normal lower alphabet
noralpha = ['a' : 'z'];
%Now we need to make a loop for matlab to check for each letter
for i = 1:length(text)
for j = 1:26
n = r(i) == natalph(j);
if noralpha(j) == text(i) : n
else r(i) = r(i)
natoText = ''
end
end
end
for v = 1:length(plaintext)
natoText = natoText + r(v) + ''
natoText = natoText(:,-1)
end
end
我知道上面的代码是一团糟,我有点怀疑我一直在做什么。有谁知道更好的方法吗?我可以修改上面的代码以使其有效吗?
因为现在当我运行代码时,我得到一个空的情节,我不知道为什么,因为我没有要求任何一行的情节。
答案 0 :(得分:2)
您实际上可以在一行中进行转换。鉴于您的string array natalph
:
plaintext = 'hello'; % Your input; could also be "hello"
natoText = strjoin(natalph(char(lower(plaintext))-96), '-');
结果:
natoText =
string
"Hotel-Echo-Lima-Lima-Oscar"
这使用了一种技巧,即字符数组可以被视为其ASCII equivalent值的数字数组。代码char(lower(plaintext))-96
将plaintext
转换为lowercase,然后转换为character array(如果尚未转换)并通过减去96将其隐式转换为ASCII值的数值向量由于'a'
等于97,因此会创建一个包含值1('a'
)到26('z'
)的索引向量。这用于索引字符串数组natalph
,然后这些是带有连字符的joined together。