Rime
Rime

Reputation: 942

How to assign names in a MATLAB loop

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 ?

Upvotes: 1

Views: 134

Answers (1)

Divakar
Divakar

Reputation: 221704

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{:});

Upvotes: 1

Related Questions