Playing with matrix and putting in number values
6 views (last 30 days)
I would like to have a matrix such as X
I have a word ABCD
this word has a sign number 12
The matrix X is made as
I have desided that it will be like:
start A B C D
start 0 0 0 0 0
A 0 0 0 0 0
B 0 0 0 0 0
C 0 0 0 0 0
D 0 0 0 0 0
I will go from start to A and put the number 12 in X(start,A) position
then I go from A to B and put the number 12 in X(A,B) position
and so on
the rows are from and columns are to
How can I put the number in those positions, and how can I tell the matrix that for example position X(3,3) should be used and put number in if, in the given word you came to something like BB, or as in this example we have ABCD, how can I tell the matrix that when you come to CD then put a value of 12 in X(4,5)?
The matrix X here needs to understand that if I start a word with A so it put a number 12 in position X(1,2) then I come to AB, so I come from A to B, so the value 12 should be put in X(2,3) and so on until ABCD word is done (which means do this once for BC and once for CD, and save the the matrix X with the new valuses of 12 it god in those positions.
A bit difficult to explain, but I hope it makes sence
Benjamin Kraus on 23 Sep 2021
There seems to be a few things missing from your description, such as where the number 12 comes from, and how you want to handle the situation where a sequence of letters is repeated (if the string was ABABABA for example). But, this code will do what you indicated, and you will have to work out the remaining details.
word = 'ABCD';
magicNumber = 12;
% Start by assigning a unique index to each unique letter.
[uniqueLetters,~,ind] = unique(word);
X = zeros(numel(uniqueLetters)+1);
% Increment the unique indices to account for the "start" index.
ind = ind(:)'+1;
% Append "1" to the beginning to indicate "start".
ind = [1 ind];
% Loop through the vector of indices, recording the pairings.
for p = 1:numel(word)
% Note this just overwrites the previous value if a pairing of letters
% is repeated.
X(ind(p),ind(p+1)) = magicNumber;
% For fun, put this into a table, so you have nice row and column headers.
labels = ["Start"; string(uniqueLetters')];
tbl = array2table(X,"RowNames", labels, "VariableNames", labels);