How to search excel document to find string and return number of row?
44 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Peter Bruinooge
le 1 Juil 2015
Commenté : Precious Chukwuezi
le 29 Déc 2023
So I am trying to access an excel file, find a certain string determined by the user input, and give me a variable with the value of its row. I'm not sure if this actually possible but I feel like it should. Say this is my excel document:
- Number Name Type 1 Type 2 Weakness 1
- 1 bulbasaur grass poison fire
...etc for the first gen pokemon. I'm looking to have the user input the name of the pokemon, then have the code search for the string, and tell me which row it is in. My goal is to have this so I don't have to hard code every single pokemon in the list. I've used [num,txt] = xlsread('pokemon'); to get the data, then validate string to set a variable equal to the string. But then I'm looking to get a number or text value for the row. So say I'm looking for bulbasaur, it should return a 2, and any other pokemon down the list will give the row number. Any help? I know I don't have much actual code here, because I'm on a different computer. But I don't think I've found the right command to do this anyway. Thanks!!
0 commentaires
Réponse acceptée
Abhiram Bhanuprakash
le 6 Juil 2015
Modifié(e) : Abhiram Bhanuprakash
le 6 Juil 2015
Hi Peter,
For your requirement, I think you can use the raw data given as output by xlsread.
In your example, if you execute the following code:
in = input('Enter pokemon name as string\n');
[num,txt,raw] = xlsread('Book1.xlsx');
p = strcmpi(in,raw(:,2));% Compare user input string with entries in the Excel sheet
rowNum = find(p==1)%Get Row number
You will see that it gives the row number 2 if you give 'bulbasaur' as input. I have attached the Excel sheet as well for your reference.
Doc links for the functions used are below:
Hope this helps,
Cheers!
Abhiram
2 commentaires
Plus de réponses (1)
Guillaume
le 6 Juil 2015
Another option to Abhiram's answer is to load the data into a table with readtable. It has the advantage of keeping the headers of your excel file and may make the indexing of column easier:
searchname = 'Bulbasaur';
pokemons = readtable('Book1.xlsx', 'ReadVariableNames', true);
selectedrow = strcmp(pokemons.Name, searchname)
0 commentaires
Voir également
Catégories
En savoir plus sur Spreadsheets dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!