2014-11-08 14 views
1

我在MATLAB中出現循環問題。如何在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]載體,使我最終提取GDXJJDST,並從stocksGLD

+0

假設你'[價格]'只會有'GDXJ',' JDST','GLD' ....你可以檢查'stocks'來查看你感興趣的元素是否是alpha。以下's = isstrprop('GDXJ','alpha')'將返回's = [1 1 1 1]'邏輯。如果你們全都是真的,你會把它提取出來嗎?那是你要的嗎? – ha9u63ar 2014-11-08 11:39:10

回答

1

看看這對你的作品 - for循環後

%% 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 

或者這結束 -

datac = arrayfun(@(x) stocks(x).AdjClose,1:col,'Uniform',0); 
[GDXJ,JDST,GLD] = deal(datac{:}); 
+0

令人驚歎的是,這兩個代碼的工作....非常感謝你 – Rime 2014-11-08 12:36:41

+0

@Rime真棒!乾杯:) – Divakar 2014-11-08 12:37:24