Get row index into matrix

I have the following line in matlab

V= 'abcdefghijklmnñopqrstuvwxyz'; 

Then I have a 9 character word consisting of characters from my "V" alphabet.

 k = 'peligroso'; 

I want to create a square matrix (3x3) with the indices of my word "k" according to my alphabet, this will be the way out. (Note that the range I'm considering is from 0 to 26, so the "a" char has index 0)

  16 4 11
    8 6 18
    15 19 15

My code for this:

 K = [findstr(V, k(1))-1 findstr(V, k(2))-1 findstr(V, k(3))-1;findstr(V, k(4))-1 findstr(V, k(5))-1 findstr(V, k(6))-1; findstr(V, k(7))-1 findstr(V, k(8))-1 findstr(V, k(9))-1]; 

But I think there should be a more elegant solution to achieve the same, any ideas?

PS: I do not use ASCII values ​​since char '-' must be inside my alphabet

+4
source share
3 answers

For a solution without a loop, you can use ISMEMBER , which works with both strings and numbers:

 K = zeros(3); %# create 3x3 array of zeros [~,K(:)] = ismember(k,V); %# fill in indices K = K'-1; %# make K conform to expected output 
+7
source

Since strings are just arrays of characters, they are easy to manipulate using the usual array processing functions.

For example, we can use arrayfun to create a new array by applying the specified function, which creates an output array of the same size. Using the formula, we can form the desired 3x3 shape. Note that we are transposing at the end, since MATLAB converts arrays to the main column order.

 K = reshape(arrayfun(@(x) findstr(V, x)-1, k), 3,3)' 

Alternatively, since MATLAB allows you to index matrices using a single index, which reads the matrix entries in the main column order, we can build an empty matrix and build its entries one at a time.

 K = zeros(3,3) for i=1:9 K(i) = findstr(V, k(i))-1; end K = K' 
+2
source

I love @Jonas ( ismember ) ismember , I think this is the most elegant way to go here. But, to provide another solution:

 V = 'abcdefghijklmnñopqrstuvwxyz'; k = 'peligroso'; K = reshape( bsxfun(@eq, (k-0).', V-0) * (1:numel(V)).', 3,3).' 

(forgive SO highlighting)

The advantage of this is that it uses exclusively built-in functions ( ismember not built-in, at least not on my Matlab R2010b). This means that this solution may be faster than ismember , but

  • You will need to check if this is true, and if it is true,

  • you must have cases complex and large enough to warrant a loss of readability ismember

Note that the indices in Matlab are based on 1, which means V(1) = a . The solution above gives an answer based on 1, while you provide an example based on 0. Just subtract 1 from the line above if you really need 0 based indexes.

+2
source

All Articles