在 MATLAB 中将字母转换为北约字母表

Converting letters into NATO alphabet in MATLAB

我想在 MATLAB 中编写一个代码,将字母转换为北约字母表。例如单词'hello'将被重写为Hotel-Echo-Lima-Lima -奥斯卡。我在使用代码时遇到了一些麻烦。到目前为止,我有以下内容:

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

我知道上面的代码很乱,我有点怀疑我到底做了什么。有谁知道这样做的更好方法吗?我可以修改上面的代码使其工作吗?

这是因为现在当我 运行 代码时,我得到一个空图,我不知道为什么,因为我没有要求任何行的图。

您实际上可以在一行中完成转换。鉴于您的 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 values. The code char(lower(plaintext))-96 converts plaintext to lowercase, then to a character array (if it isn't already) and implicitly converts it to a numeric vector of ASCII values by subtracting 96. Since 'a' is equal to 97, this creates an index vector containing the values 1 ('a') through 26 ('z'). This is used to index the string array natalph, and these are then joined together 带有连字符的数字数组。