Find a value in excel file
Mostra commenti meno recenti
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?
Risposta accettata
Più risposte (2)
Image Analyst
il 15 Ago 2014
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
il 27 Mag 2020
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...
Categorie
Scopri di più su Data Import from MATLAB in Centro assistenza e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!