MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today
Asked by C Zeng on 24 Dec 2012

Hi I have a database with cost assigned to over 500 zipcodes, that is, one zipcode has a corresponding cost. I want to build a function in matlab, that each time I have a zipcode it will return the cost. Is there a way to do it efficiently?

I have a plan to build a matrix, each row has a zipcode and a cost. I can input it but when I find it I need to go over all zipcodes to find the cost. Zipcodes are not consecutive by the way.

Thanks.

*No products are associated with this question.*

Answer by Laura Proctor on 24 Dec 2012

Edited by Laura Proctor on 24 Dec 2012

Accepted answer

If you have the Statistics Toolbox, you could use a dataset array.

% Create a sample dataset x = dataset({(1:10)','ZipCodes'},{rand(10,1),'Cost'}) % Find the cost value associated with the ZipCode value of 5 x.Cost(x.ZipCodes==5)

Alternatively, you could use a map container, which allows you to just look up your cost by inputting the Zip Code value:

% Create a sample map container object mapObj = containers.Map((1:10)',rand(10,1)) % Look up the cost associated with the ZipCode value of 5 mapObj(5)

C Zeng on 24 Dec 2012

Thanks, Laura. However my zip code is 5 digits, and not consecutive, can I store zipcode and the cost in matlab file? Or I need to input them by myself?

Laura Proctor on 24 Dec 2012

Nonconsecutive values will work for both cases. I'm assuming that you already have the values in some sort of document which you should be able to import into MATLAB with the import tool (depending on the version of MATLAB you are using) as variables and then use those variables as inputs to whichever function you choose to use.

Answer by Image Analyst on 24 Dec 2012

Why not just have a simple 500 by 2 numerical matrix to store the zip codes and the costs? Say you call it "zipCodeLookUpTable". Each row lists the zip code (in the first column) and the cost (in the second column). Then if you want to find the cost of a zip code, say it's called thisZipCode, find the row by looking in the first column, and then get the cost from the second column:

% Get the row where this zip code is located. row = find(zipCodeLookUpTable(:,1) == thisZipCode); % Get cost for this zip code. cost = zipCodeLookUpTable(row, 2);

Show 2 older comments

C Zeng on 25 Dec 2012

Thanks, I use save('XLSFile'...) and now I can do it. I recall in my algorithm class that there should be a better find algorithm using divide and conquer, but I think it is fine.

Image Analyst on 26 Dec 2012

save() will save MATLAB data out to a disk file in a proprietary MATLAB format .mat file. It **will not import data** in an Excel file into MATLAB.

## 0 Comments