Matlab字符向量莫名转为N*N数组——移位密码函数调用异常求助
移位密码加密函数主脚本调用返回N*N数组的问题分析与解决
问题描述
在信息安全课程中实现移位密码加密的encrypt函数,单独运行时输入字符向量可正常得到预期的密文字符向量;但主脚本调用时输入如'testing'这类字符向量,返回的却是N*N字符数组,输出异常。
函数代码
function ciphertext = encrypt(plaintext, k) %first, call the "double" function on the plaintext %this converts it to numbers for ASCII usage %we add k to all these numbers asciivec = double(plaintext); for i = 1:length(asciivec) if (asciivec(i) + k) > 90 diff = (asciivec(i) + k) - 90; adjustedvec(i) = 64 + diff; else adjustedvec(i) = asciivec(i) + k; end end %vector is adjusted, convert back to characters ciphertext = char(adjustedvec); return
主脚本代码
clc plaintext = 'SSOEATBENEDUMHALLOHARASTREET'; k = 3; secrets = encrypt(plaintext, k);
问题原因
核心问题是函数中的adjustedvec变量未预先初始化维度。在Matlab中,未提前定义维度的变量会在循环赋值时动态扩展:
- 单独运行函数时,Matlab会创建全新的函数工作区,
adjustedvec从无到有,动态扩展为一维向量,结果符合预期; - 主脚本调用时,若函数工作区因之前的调试、运行残留等情况,导致
adjustedvec被意外初始化为二维数组,后续循环赋值会持续扩展为NN的二维结构,最终char(adjustedvec)转换后得到NN字符数组。
解决方案
在函数中asciivec = double(plaintext);之后,添加代码预先初始化adjustedvec,使其维度与asciivec完全一致:
修改后的完整函数代码
function ciphertext = encrypt(plaintext, k) %first, call the "double" function on the plaintext %this converts it to numbers for ASCII usage %we add k to all these numbers asciivec = double(plaintext); adjustedvec = zeros(size(asciivec)); % 预先初始化维度,确保与输入向量同结构 for i = 1:length(asciivec) if (asciivec(i) + k) > 90 diff = (asciivec(i) + k) - 90; adjustedvec(i) = 64 + diff; else adjustedvec(i) = asciivec(i) + k; end end %vector is adjusted, convert back to characters ciphertext = char(adjustedvec); return
额外说明
当前函数仅支持大写字母的移位加密,若输入小写字母会得到非预期符号(比如'testing'为小写,ASCII值大于90,会被转换为其他符号)。如果需要支持小写字母,可以添加对小写字母ASCII范围(97-122)的判断逻辑。
内容的提问来源于stack exchange,提问作者arm618
相关产品推荐
相关产品推荐

