How can I find each character's index within a matrix, from a vector of characters?

9 vues (au cours des 30 derniers jours)
Mackenna Landis
Mackenna Landis le 28 Avr 2023
Réponse apportée : DGM le 28 Avr 2023
I have a matrix of characters
Letters = [A, B, C;
D, E, F;
G, H, I];
Secondarily, I will have a vector of letters, and I need to find the index of each letter in the matrix of Letters. For example,
vec = [A, C, H, I], or it could be any combination of letters. I'm sure there is a simple answer that I am missing. I know normally you need to call the character with a string, but I don't know how to call, say vec(1) as a string (as in, idx = find(Letters == vec(1)), and it would return 1, for A), which I think would solve the problem.

Réponses (2)

Chunru
Chunru le 28 Avr 2023
Letters =['ABC'; 'DEF'; 'GHI']
Letters = 3×3 char array
'ABC' 'DEF' 'GHI'
vec = 'ACHI'
vec = 'ACHI'
for i=1:length(vec)
[r, c] = find(Letters == vec(i));
fprintf("%s: (%d, %d)\n", vec(i), r, c)
end
A: (1, 1) C: (1, 3) H: (3, 2) I: (3, 3)

DGM
DGM le 28 Avr 2023
If you're talking strictly about character arrays, then:
Letters = ['ABC'; 'DEF'; 'HIJ'];
vec = 'ACHI';
[~, idx] = ismember(vec,Letters) % idx is a linear index into Letters
idx = 1×4
1 7 3 6

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by