【发布时间】:2015-04-03 11:49:24
【问题描述】:
Matlab 新手,正在尝试将二进制消息转换为 Matlab 中的字符。我能够将二进制消息转换为十进制的单列(没有 bin2dec 函数,因为我被指示不要这样做),每个数字对应于字符串数组中的一个字符。
我无法让字符串数组在另一个数组的索引值处显示其值。它在我引用数组的单个索引时有效(例如 message = char_array(decimal(1)) 返回值 k),但在我尝试引用整列或整个十进制数组(例如 message = char_array(decimal(:,:)) 和 message = char_array(decimal(:,1)) 不起作用并给出相同的错误)。我知道这可以通过 for 循环 完成,但我们被指示不要使用这些。
是否有其他技巧可以一次显示整个消息?这需要以这样一种方式工作,即它可以通过一行简单的代码一次用于数千个字母。
到目前为止的代码:
clear;clc
% Array of characters (first value is a space, last is ! which denotes the end of the message)
char_array = ' abcdefghijklmnopqrstuvwxyz!';
% The secret message in binary
secret = [0 1 1 0 0;
0 0 0 0 1;
1 0 0 0 0;
0 1 0 0 0;
1 0 0 1 0;
0 1 1 1 1;
0 0 0 0 1;
0 1 0 0 1;
0 0 1 1 1;
0 0 0 0 0;
1 0 0 1 0;
0 1 1 1 1;
0 0 0 1 1;
0 1 0 1 1;
1 0 0 1 1;
1 1 0 1 1];
% Assigns a decimal value to each column to help convert binary values to decimal
conv = [16 8 4 2 1];
% Converts binary numbers in each column of secret message to a decimal value
convert = [secret(:,1)*conv(1), secret(:,2)*conv(2), secret(:,3)*conv(3), secret(:,4)*conv(4), secret(:,5)*conv(5)];
% Converts unadded decimal values into columns to prepare for addition
binary = convert';
% Adds numbers in each column, then transposes it to a single column of decimal values representing values of each row of original message
decimal = sum(binary)';
% Should display character from character array for each index value of "decimal", but returns "Subscript indices must either be real positive integers or logicals." error each time. Works for individual entries such as decimal(1), though.
message = char_array(decimal(:,:))
【问题讨论】: