2014-11-08 42 views
0

我試圖運行下面的代碼通過在一個循環的整數:如何使用MATLAB

%% Getting Stocks 
stocks = hist_stock_data('01012013','07112014','GDXJ', 'SPY','GOOGL', 'QQQ', 'AAPL'); 

%% Loop to get the stocks in order by date 
while i <= 5 

stocks(1,i).Date=datenum(stocks(1,i).Date); 
stocks(1,i).Date = stocks(1,i).Date(end:-1:1); 
stocks(1,i).AdjClose = stocks(1,i).AdjClose(end:-1:1); 
stocks(1,i).Ticker =stocks(1,i).AdjClose; 
end 

但是我收到以下錯誤:

Subscript indices must either be real positive integers or logicals.

我已經在網上搜索但不明白爲什麼我得到這個錯誤?

回答

0

首先,你必須提到hist_stock_data是一個你從外部獲得的函數,它不是MATLAB的內建函數或變量。那麼,我GOOGLE了它,並發現它在MATLAB File Exchange

接下來看代碼,這裏有一些建議 - 儘量避免使用i作爲迭代器,因爲當未初始化的MATLAB會認爲它是imaginary unit。詳細瞭解它here。這就是爲什麼你得到這個錯誤 - Subscript indices must either be real positive integers or logicals.,因爲正在使用的索引是不能用作索引的imaginary unit

所以,我們可以改變i爲類似ii -

while ii <= 2 
    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); 
    stocks(1,ii).Tiicker =stocks(1,ii).AdjClose; 
end 

然後,我們運行代碼,看看這個錯誤 -

Undefined function or variable 'ii'. 

現在,我做了一些猜測,取而代之的是while-loopfor-loop迭代結構stocks中的所有元素。因此,它成爲 -

for ii = 1:numel(stocks) 
    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); 
    stocks(1,ii).Tiicker =stocks(1,ii).AdjClose; 
end 

這運行正常,但要確保結果是你要找什麼,有stocks

如果你希望運行只有第一5元素循環,然後做到這一點 -

for ii = 1:5 
+0

感謝,真正幫助! – Rime 2014-11-08 08:02:38