我在MATLAB中循环时遇到问题。
%% Getting Stocks
stocks = hist_stock_data('01012013','07112014','GDXJ', 'JDST', 'GLD');
这是我要循环的块
% STOCK #1
stocks(1,1).Date=datenum(stocks(1,1).Date);
stocks(1,1).Date = stocks(1,1).Date(end:-1:1);
stocks(1,1).AdjClose = stocks(1,1).AdjClose(end:-1:1);
GDXJ=stocks(1,1).AdjClose;
% STOCK #2
stocks(1,2).Date=datenum(stocks(1,2).Date);
stocks(1,2).Date = stocks(1,2).Date(end:-1:1);
stocks(1,2).AdjClose = stocks(1,2).AdjClose(end:-1:1);
JDST=stocks(1,2).AdjClose;
% STOCK #3
stocks(1,3).Date=datenum(stocks(1,3).Date);
stocks(1,3).Date = stocks(1,3).Date(end:-1:1);
stocks(1,3).AdjClose = stocks(1,3).AdjClose(end:-1:1);
GLD=stocks(1,3).AdjClose;
我遇到的唯一问题是分配名称,以便将stocks
中的向量提取到我的工作区。这是我目前拥有的:
%% Extract number of Columns
[row, col] = size(stocks);
%% Different Loop
for ii = 1:col
stocks(1,ii).Date=datenum(stocks(1,ii).Date);
stocks(1,ii).Date = stocks(1,ii).Date(end:-1:1);
stocks(1,ii).AdjClose = stocks(1,ii).AdjClose(end:-1:1);
[Prices] = stocks(1,ii).AdjClose;
end
如何为上面的[Prices]
向量指定名称,以便最终从GDXJ
中提取JDST
,GLD
和stocks
?
答案 0 :(得分:1)
看看这是否适合你 -
%% Getting Stocks
stocks = hist_stock_data('01012013','07112014','GDXJ', 'JDST', 'GLD');
%% Extract number of Columns
[row, col] = size(stocks);
%% Different Loop
for ii = 1:col
stocks(1,ii).Date=datenum(stocks(1,ii).Date);
stocks(1,ii).Date = stocks(1,ii).Date(end:-1:1);
stocks(1,ii).AdjClose = stocks(1,ii).AdjClose(end:-1:1);
end
fnms = fieldnames(stocks); %// get fieldnames
datac = struct2cell(stocks); %// convert struct to cell
[GDXJ,JDST,GLD] = deal(datac{strcmp(fnms,'AdjClose'),:}); %// get only the relevant
%// fieldname data from the cell
或者在for循环结束后 -
datac = arrayfun(@(x) stocks(x).AdjClose,1:col,'Uniform',0);
[GDXJ,JDST,GLD] = deal(datac{:});