where in my code I am thinking wrong?

1 vue (au cours des 30 derniers jours)
Manav Divekar
Manav Divekar le 29 Nov 2021
Commenté : Jan le 30 Nov 2021
I am trying to read data from the excel file, and return the age.
function [age] = xls_ageofperson (excelname, name)
[data text]= readtable(excelname);
ii=0;
jj=0;
for i = 1: length(data)
if string(name)==string(txt{1,i})
ii=i;
end
if (string(text)==string(txt{2,i}))
jj=i;
end
end
age = i;
if i input any name in the command window i am expecting it to return its age.

Réponses (1)

Jan
Jan le 29 Nov 2021
  • length() is fragile: It uses to longer dimension. You cannot be sure if your table has more rows than columns. Use height() instead or size(data, 1) in older Matlab versions.
  • readtable has 1 output only So what do you expect text to be?
[data text]= readtable(excelname);
  • Your code replies the value of i as age, but the value of i comes from the last iteration of the loop:
age = i;
So age is always the number of rows of the table. But what are ii and jj good for?
I assume, you want:
function age = xls_ageofperson(excelname, name)
data = readtable(excelname);
age = data.age(data.name == name);
end
  2 commentaires
Manav Divekar
Manav Divekar le 29 Nov 2021
Error i am getting
>> [age] = xls_ageofperson('crps_data_fakenames.xlsx','Aniya Abbott')
Warning: Column headers from the file were modified to make them valid MATLAB
identifiers before creating variable names for the table. The original column headers
are saved in the VariableDescriptions property.
Set 'VariableNamingRule' to 'preserve' to use the original column headers as table
variable names.
Operator '==' is not supported for operands of type 'cell'.
Error in xls_ageofperson (line 4)
age = data.age(data.Name == Name);
Jan
Jan le 30 Nov 2021
Okay. Does this mean that data.Name is a cell or Name? You can check this easily. Try this:
age = data.age(strcmp(data.Name, Name));

Connectez-vous pour commenter.

Catégories

En savoir plus sur Data Import from MATLAB dans Help Center et File Exchange

Tags

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by