MATLAB,从字符串到矩阵获取用户输入

时间:2016-04-08 19:24:41

标签: matlab matrix input

A = (32:127);
S = char(A);
S = reshape(S,32,3)'



prompt = {'Enter a sentence you would like to Encrypt'};
dlg_title = 'Input';
num_lines = 1;
defaultans = {'Hello'};
answer = inputdlg(prompt,dlg_title,num_lines,defaultans);

我正在为一个类编写一个简单的加密应用程序。我需要使用矩阵来实现。我让用户在字符串中输入内容但是如何让它们将其输入矩阵或将字符串转换为矩阵?

2 个答案:

答案 0 :(得分:1)

inputdlg函数将返回a cell array of string。您可以使用以下命令将inputdlg的返回值转换为字符串:

answer = answer{1}

答案 1 :(得分:0)

prompt = 'Enter a sentence you would like to Encrypt';
dlg_title = 'Input';
num_lines = 1;
defaultans = {'Hello'};
answer = inputdlg(prompt,dlg_title,num_lines,defaultans);

answer = answer{1}; % Coverts cell to String like hungptit said

% find out how big the square matrix for data should be
for i = 1:length(answer) % it should never run this far anyway
   if (i^2) > length(answer) 
       break;
   end
end

mat_len = i; 

% predefine square matrix of numbers forcing matrixA to number type
matrixA = zeros(mat_len,mat_len); 

% iterate through square matrix assigning answer values to positions
for i = 1:mat_len
    for j = 1:mat_len
        if (((i-1)*mat_len)+j) <= length(answer)
            matrixA(i,j) = answer(((i-1)*mat_len)+j);
        else
            break;
        end
    end
end

这是一个经过编辑的答案,显示了原始问题之后的另一个步骤。

“MatrixA”将是一个方形矩阵,输入中的每个字母分配给矩阵中的一个位置,然后强制成一个数字。

您现在可以处理加密的数字。