1

I am having problems looping in MATLAB.

%% Getting Stocks
stocks = hist_stock_data('01012013','07112014','GDXJ', 'JDST', 'GLD');

This is the chunk I want to loop

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

The only problem I am having is assigning names so that I extract the vector from stocks unto my workspace. Here is what i currently have:

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

How can I assign names to the [Prices] vector above so that i end up extracting GDXJ, JDST, and GLD from stocks ?

1
  • Assuming that your [Prices] will only have the GDXJ,JDST, GLD....you can check the stocks to see if the element you are interested in is an alpha. The following s = isstrprop('GDXJ', 'alpha') will return s = [1 1 1 1] logical. If you all(s) is true, you get it extracted ? Is that what you want? Commented Nov 8, 2014 at 11:39

1 Answer 1

1

See if this works for you -

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

Or this after the for-loop ends -

datac = arrayfun(@(x) stocks(x).AdjClose,1:col,'Uniform',0);
[GDXJ,JDST,GLD] = deal(datac{:});
Sign up to request clarification or add additional context in comments.

1 Comment

@Rime Awesome! Cheers :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.