【问题标题】:Converting a cell to matrix in the presence of a for loop在存在 for 循环的情况下将单元格转换为矩阵
【发布时间】:2019-11-21 22:06:00
【问题描述】:

我在 for 循环旁边运行 LASSO 估计方法。

代码如下:

%Lasso    
data = rand(246,3);        %random data for illistrative purposes
XL1 = lagmatrix(data,1);   %Lags the data matrix by one period
ydata = data;              %Specifies the dependent variable
ydata([1],:)=[];           %Removes the top row due to the lagged X
XL1([1],:)=[];             %Removes the top row of the lagged X with become a NaN from lagmatrix
for ii = 1:3               %For loop to complete LASSO for all industries
    y = ydata(:,ii);           %y is the industry we are trying to forecast
    rng default                % For reproducibility, as the LASSO uses some random numbers
    [B,FitInfo] = lasso([XL1],y,'CV',10,'PredictorNames',{'x1','x2','x3'});
    idxLambdaMinMSE = FitInfo.IndexMinMSE;
    ii
    minMSEModelPredictors = FitInfo.PredictorNames(B(:,idxLambdaMinMSE)~=0)
end

LASSO 提供的输出是

ii = 1    
minMSEModelPredictors =    
  1×1 cell array    
{'x2'}

ii =  2
minMSEModelPredictors =
  1×5 cell array
{'x1'}    {'x2'}    {'x3'}

ii = 3
minMSEModelPredictors =
  1×2 cell array
{'x2'}    {'x3'} 

出于自动化的目的,我需要以以下方式报告结果,

Results = {[2],[1 2 3],[2 3]};

我知道这是一个长镜头,但它会有所帮助,因为上面很容易输入,但如果我增加尺寸,这将成为一项非常困难的任务。

【问题讨论】:

    标签: matlab for-loop cell-array


    【解决方案1】:

    minMSEModelPredictors 的每个输出都是一个单元格数组,格式为

    minMSEModelPredictors  = {'x1', 'x2', 'x3'};
    

    我们可以使用strrep 去除'x'(或者只是在您的预测变量名称中没有'x' 开头),并使用str2double 将元胞数组转换为数值数组.

    那么存储结果就很简单了……

    Result = cell(1,3); % Initialise output
    for ii = 1:3
        % stuff...
        minMSEModelPredictors = FitInfo.PredictorNames(B(:,idxLambdaMinMSE)~=0);
    
        Result{ii} = str2double( strrep( minMSEModelPredictors, 'x', '' ) );
    end
    

    【讨论】:

      猜你喜欢
      • 2018-09-30
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 2020-05-12
      • 2019-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多