0

I am trying to run the following code:

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

However I am getting the following error:

Subscript indices must either be real positive integers or logicals.

I have searched the web but do not really understand why I am getting this error?

Rime
  • 912
  • 2
  • 11
  • 39

1 Answers1

0

First off, you must have mentioned that hist_stock_data is a function that you got from an external source and isn't a MATLAB builtin function or variable. Well, I googled for it and found it on MATLAB File Exchange.

Next up looking at the code, here's some advice - Try to avoid using i as an iterator because when uninitialized MATLAB would consider it as the imaginary unit. Read more about it here. That's why you were getting that error - Subscript indices must either be real positive integers or logicals., because the index being used was the imaginary unit that can't be used as an index.

So, we could change i to something like 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

Then, we run the code and see this error -

Undefined function or variable 'ii'.

Now, I made some guesswork and replaced that while-loop with a for-loop that iterates for all the elements in the struct stocks. So, it becomes -

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

This runs fine, but make sure the results are what you were looking to have in stocks.

If you were looking to run the loop for the first 5 elements only, then do this -

for ii = 1:5
Community
  • 1
  • 1
Divakar
  • 218,885
  • 19
  • 262
  • 358