我在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]};
我知道这是一个很长的路,但是因为上面的内容很容易输入,所以会很有帮助,但是如果我增加尺寸,这将成为一项非常困难的任务。
答案 0 :(得分:2)
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