问题
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:
Lets say we had an Excel spreadsheet containing three sheets, each contains a series of dates and some corresponding values:
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')
回答2:
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.
来源:https://stackoverflow.com/questions/11914891/converting-date-from-excel-to-matlab-in-multiple-fields