0

I have a structure (gilts) in matlab with many fields (gilt_name). The structure is an imported workbook from excel, and each field corresponds to a worksheet in that workbook. Each worksheet is a time series of dates and corresponding prices of gilts. I converted the dates in excel to strings before importing into matlab as instructed in When to Convert Dates from Excel Files. But how do I apply this conversion to many fields simultaneously in matlab? I have hundreds of arrays of data corresponding to each gilt_name and it would save me lot of time. Many thanks.

1
  • it would be helpful if you give a concrete example of how the variable are stored (matrix/cell-array, ...). Show us the code you use to import the data and an extract of the result Commented Aug 11, 2012 at 14:18

2 Answers 2

2

Lets say we had an Excel spreadsheet containing three sheets, each contains a series of dates and some corresponding values:

excel

Consider the following code to import the data into MATLAB:

%# for each of the three sheets
data = cell(3,1);
for i=1:3
    %# read the sheet as unprocessed data (both text and numeric)
    [~,~,raw] = xlsread('data.xlsx', i);

    %# parse strings as serial dates and combine into a matrix
    data{i} = [datenum(raw(:,1),'dd/mm/yyyy') cell2mat(raw(:,2))];
end

Now each cell in the cell array data has the data of the i-th sheet. Dates are represented as serial date numbers. For example we can plot the first time series as:

plot(data{1}(:,1), data{1}(:,2))
datetick('x', 'dd', 'keepticks')
xlabel('days'), ylabel('prices')

screenshot

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

1 Comment

forgot to say, you can always go back to string representation using DATESTR function: datestr(data{1}(:,1))
1

Hey you can make a list of your field names

names = fieldnames(gilts)

And then all you need to do is cycle through in a for loop accessing the names variable by an incremental counter.

For instance,

names = fieldnames(gilts);
for i = 1 : length(gilts),
   n = [gilts(i,1). 'names(i)' (:,:)];
   eval(n); % and do what you need to do
end

So this way you can index the strings in "names" as the fields of gilts.

1 Comment

no need for the EVAL call (in fact try to always avoid it); MATLAB structures support dynamic field names: gilts(m).(names{n})

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.