Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get string index into matrix

Tags:

matlab

I have the following string in matlab

V= 'abcdefghijklmnñopqrstuvwxyz';

Then I have a word of 9 characters consisting of chars 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 would be the output. (Note that the range I'm considering is 0 to 26, so 'a' char does have index 0)

   16    4     11
   8     6     18
   15    19    15

My code for doing this is:

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 must be a more elegant solution to achieve the same, any ideas?

PS: I'm not using ASCII values since char 'ñ' must be inside my alphabet

like image 983
Jorge Zapata Avatar asked Dec 20 '22 17:12

Jorge Zapata


1 Answers

For a loop-free solution, you can use ISMEMBER, which works on strings as well as on 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
like image 195
Jonas Avatar answered Jan 02 '23 15:01

Jonas