Match numbers with letters
Mostrar comentarios más antiguos
I need to find the name score of the names in a text file.
name point: David --> 4 1 22 9 4 = 4+1+22+9+4 = 40
Thanks for your help.
2 comentarios
dpb
el 29 de En. de 2021
What have you tried?
Philippe Lebel
el 29 de En. de 2021
as there are many solutions posted that answer your question, i'd suggest to mark your question as answered.
Respuesta aceptada
Más respuestas (2)
Name = 'David';
Num = lower(Name) - 'a' + 1; % 'a' -> 1, 'b' -> 2, ...
Score = sum(Num);
[EDITED] You mention in comments, that you want to do this for "names in a text file". Do the files contain one name per line?
Str = fileread('YourTextFile.txt');
Str(Str == char(13)) = [];
CStr = strsplit(Str, char(10));
Score = zeros(size(CStr));
for k = 1:numel(CStr)
Score(k) = sum(lower(CStr{k}) - 'a' + 1);
end
4 comentarios
Mathieu NOE
el 29 de En. de 2021
I cannot fight against Jan, he's really too good ...
Score = sum(Num(Num>0)); % just avoid taking blanks into account
Pax Azx
el 29 de En. de 2021
Jan
el 30 de En. de 2021
@Mathieu NOE: I'm very happy that we are fighting together to get the best solution for the question. Seeing different approachs is useful to understand the power of MATLAB.
Mathieu NOE
el 1 de Feb. de 2021
@Jan : tx for your nice comments , but I'm not yet to your level - still I like to see how tricky problems can be solved elegantly by knowledgable people like you and others contributors here.
Philippe Lebel
el 29 de En. de 2021
im late to the show, but here we go anyway...
clear
clc
name = 'david';
a = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
total = 0;
for i=1:length(name)
arr = cellfun(@(x)isequal(x,name(i)),a);
[row,col] = find(arr);
total = total + col
end
Categorías
Más información sobre Language Support en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!