Find a value in excel file
이전 댓글 표시
Hi everybody! Hope that somebody can help me, I'm relative new to matlab and are wondering if I have an excel file with a table containing both names an numbers, and I want to use a number related to one of the names in a function when the name is an input argument, am I supposed to use a loop or what?
EX:
Name Bought Sold
Eric 2 13
Linda 7 4
Jasmine 3 8
Fredrik 10 9
I want to have the name as an argument ex:
Function CalculateTotal (name)
The function should then "find" the right name and use the values related to that person so that for exampel;
CalculateTotal (Eric)
Should be 2+13=15
Any one who can help me?
채택된 답변
추가 답변 (2개)
Image Analyst
2014년 8월 15일
I think the simplest, cleanest, and most elegant way is to use a table. This works great but only if you have version R2013b or later:
function test2
% The main routine.
clc;
t = readtable('D:\Temporary stuff\Book1.xlsx')
% Call the function
[numberBought, numberSold] = CalculateTotal('Eric', t)
% The function definition.
function [bought, sold] = CalculateTotal(personName, t)
row = ismember(personName, t.Name) % Find row where this person is stored.
if row > 0
bought = t.Bought(row);
sold = t.Sold(row);
else
% Name was not found.
sold = 0;
bought = 0;
end
Of course you can make it more robust by calling lower() to make it case insensitive, using try catch, alerting user with warndlg() if the name is not found, handling the case where the same name shows up in multiple rows, etc.
Bereketab Gulai
2020년 5월 27일
Alternative with actxserver:
excelApp = actxserver("excel.Application");
excelApp.Visible = false;
book1 = excelApp.Workbooks.Open('D:\Temporary stuff\Book1.xlsx');
% Sheet item 1 ...
sheetOne = book1.Sheets.Item(1);
foundInterfaceObj = sheetOne.Range("A:A").Find('Eric');
The returned Interface provides lots functions you may need. Row will give the row number, Value for the cell...
카테고리
도움말 센터 및 File Exchange에서 Data Import from MATLAB에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!