How to determine a matrix presenting the number of times that element j appears at position i, and the number of times that element j appears immediately after k?

1 visualizzazione (ultimi 30 giorni)
Suppose, j=6 elements = 11, 12, 13, 21, 22, 23
X, Y, Z are three arrays containing the permutation of j elements.
X = [11 22 21 13 12 23]
Y = [11 13 21 23 22 12]
Z = [21 12 11 13 23 22]
How can I determine a matrix (A) from X, Y, Z representing the number of times that element j appears at position i (=1,2,3,4,5,6)?
A would be j*i matrix. The answer would be:
A = [A11 A12 A13 A14 A15 A16
A21 A22 A23 A24 A25 A26
A31 A32 A33 A34 A35 A36
A41 A42 A43 A44 A45 A46
A51 A52 A53 A54 A55 A56
A61 A62 A63 A64 A65 A66]
= [2 0 1 0 0 0
0 1 0 0 1 1
0 1 0 2 0 0
1 0 2 0 0 0
0 1 0 0 1 1
0 0 0 1 1 1]
Let j=k.
How can I determine a matrix (B) from X, Y, Z representing the number of times that element j appears immediately after k (where j ~= k)?
B = [- 1 0 1 0 0
2 - 2 3 2 1
3 1 - 2 1 0
2 0 1 - 1 0
3 1 2 2 - 2
3 2 3 3 1 -]

Risposta accettata

Simon Chan
Simon Chan il 20 Feb 2022
Use function ismember and create a counter to accumulate the number of occurance
S = [11, 12, 13, 21, 22, 23];
X = [11 22 21 13 12 23];
Y = [11 13 21 23 22 12];
Z = [21 12 11 13 23 22];
K = [X;Y;Z];
index = arrayfun(@(t) ismember(K,t),S,'uni',0); % Find the position index
A = cell2mat(cellfun(@sum,index,'uni',0)')
A = 6×6
2 0 1 0 0 0 0 1 0 0 1 1 0 1 0 2 0 0 1 0 2 0 0 0 0 1 0 0 1 1 0 0 0 1 1 1
%
B = zeros(numel(S),numel(S)); % Initialize counter B
for n = 1:numel(S)
[row,col] = find(index{n}); % Find the row and column number of the specific number
for k = 1:size(K,1)
data = K(row(k),1:col(k)); % Extract the numbers in front of the specific number
B(n,:) = B(n,:) + ismember(S,data); % Add the number in the counter
end
B(n,n)=NaN; % Set own counts to NaN
end
B
B = 6×6
NaN 1 0 1 0 0 2 NaN 2 3 2 1 3 1 NaN 2 1 0 2 0 1 NaN 1 0 3 1 2 2 NaN 2 3 2 3 3 1 NaN

Più risposte (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by