0

我正在处理一个项目欧拉问题,它要求我对名称的文本文件进行排序,然后根据其字母位置(即'Bob' = 2、15、2)为名称中的每个字母分配一个值。

我正在考虑使用 excel 中的 VLOOKUP 函数之类的方法来解决问题。我想用字母表中的字母按字母顺序创建一个参考列向量 - 每个字母在参考向量中的位置都是它的“值”。然后我可以在我的名字表中输入一个条目,比如“BOB”,并在参考向量中查找值 B、O 和 B,输出它们的位置以及每个字母的值。

我的问题:如何将一个矩阵中的值引用到另一个向量中的值?感谢大家对此的帮助。

4

2 回答 2

1

Unless performance is a real concern here, I wouldn't bother with a lookup table. There's a simple way to convert your characters into numbers.

Take each of your strings, upper case them using upper, subtract off 'A' and add one to convert all 'A's into '1's, 'B's into '2's, etc.

s = 'Bob';
num_s = upper(s) - 'A' + 1;

I am still curious maybe for my own development to learn how to examine a character, match it to an entry in another vector and recall a value it corresponds to. – user1499689

To do this is easy in Matlab. Let's say you have a lookup table of 26 elements, lookup

lookup = zeros(26,1);
% define the lookup table
for i=1:numel(lookup)
  lookup(i) = 2*i - 7;   % some random function
end

Now, using the char-to-number conversion above:

s =

Joe

>> lookup( upper(s) - 'A' + 1 )

ans =

    13
    23
     3

The key here is that Matlab allows you to index any matrix with another matrix: M(A). The elements of the matrix A are treated as indices into the matrix M. Your string s is a char matrix, which you convert into a numeric matrix by subtracting 'A'. The line lookup(...) then uses the elements of this converted matrix to index the matrix lookup.

This, incidentally, can be used for assignment as well. For example, if you wanted to keep a count of each character (independent of case):

% Initialize counts to zero somewhere at the beginning
counts = zeros(26,1);

... % do your stuff

% let 's' be an alphabetic word (only A-Z and a-z)
s_inds = upper(s) - 'A' + 1;
counts( s_inds ) = counts( s_inds ) + 1;  % increment the counts of all characters in 's'
于 2012-07-03T19:02:22.017 回答
0

您将需要一种生成各种查找表的方法。我们将使用您在此处的一般示例。字母表中有 26 个字母,不区分大小写。

Basic_lookup = 1:26; % Note: this can be changed up if you want some level of randomness.
% Basic_lookup = randperm(26); % I like this a bit better for randomness sake.  And is just an example of making it random.

现在这是一个从 1 到 26 的单行向量。您需要做的只是逐个检查具有值的字符串,然后从查找表中调用所需的值。@sfstewman 在他们的帖子中在某种程度上详细说明了这一点。你可以很容易地从中适应。

于 2012-07-03T19:06:04.623 回答