2

I need to import certain columns from an Excel spreadsheet into Matlab and save the result in an array.

For example, say I have a 3x1 cell array and the elements are strings like 'USD', 'EUR' and 'GBP'.

if I want to import data from 3 separate spreadsheets on a network share and store the data from each spreadsheet in arrays called 'InitialUSD', 'InitialEUR' and 'InitialGBP' respectively.

Any guidance on how I could get the array names to be linked to the values in the cell array?

1
  • If you don't have trouble in getting the data, but only the linking. Consider using a struct. Then you can have 1 field with values and 1 field with the corresponding name. In your case this would mean a 3x1 struct of which each element contains 1 vector (or Nx1 cell array) and 1 string. Commented Sep 12, 2013 at 10:23

3 Answers 3

3

You probably want something like this:

currencies = {'USD' 'EUR' 'GBP' };
for index=1:length(currencies)
    assignin('caller',['Initial' currencies{index}],1:index);
end

In the example, I'm assigning a vector (1:index) to the variables but obviously in your case you'd be assiging the excel data (presumably that you're reading with xlsread).

Sign up to request clarification or add additional context in comments.

Comments

3

Is what you're asking How can I create variables A1, A2,...,A10 in a loop? Then, the answer is don't do this... You can however do something like this:

for k=1:3
   InitialUSD{k} = xlsread (%spreadsheet nb. k%);
end

assuming you are using xlsread to import your data from Excel. Replace %spreadsheet nb. k% by the correct arguments to the xlsread function.

3 Comments

It looks like the code in your answer is attempting to assign the return value from xlsread to a string. Have you tried this? I think you'll get an error.
Say I don't want any digits in the variable name. Instead I want the variable names to include the name of the currency whose data it holds.
@Fayyaadh Depending on which version of MATLAB you use, you can maybe define an enumeration class and use that to index into your cell array. See mathworks.co.uk/help/matlab/matlab_oop/enumerations.html for more details and some examples.
1

I think this is a straightforward way to do it:

  1. Read everything from the excel file
  2. Compare the information from the header rows with the ones that you are interested in
  3. Based on this, select the data that you want.

This way you can end up with a list of names, and an array with matching data in the same order.

I would always recommend this over giving the variables names themselves.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.