where in my code I am thinking wrong?
이전 댓글 표시
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.
답변 (1개)
Jan
2021년 11월 29일
- 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
Manav Divekar
2021년 11월 29일
Jan
2021년 11월 30일
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));
카테고리
도움말 센터 및 File Exchange에서 Tables에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!