【问题标题】:How to assign names in a MATLAB loop如何在 MATLAB 循环中分配名称
【发布时间】:2014-11-08 19:55:59
【问题描述】:

我在 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] 向量分配名称,以便最终从stocks 中提取GDXJJDSTGLD

【问题讨论】:

  • 假设你的[Prices]只有GDXJ,JDST,GLD....你可以查看stocks看看你感兴趣的元素是不是一个阿尔法。以下s = isstrprop('GDXJ', 'alpha') 将返回s = [1 1 1 1] 逻辑。如果你all(s) 是真的,你把它提取出来了吗?这就是你想要的吗?

标签: matlab loops


【解决方案1】:

看看这是否适合你 -

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

或者这个for循环结束后-

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

【讨论】:

  • @Rime 太棒了!干杯:)
猜你喜欢
  • 2020-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-29
相关资源
最近更新 更多