在存在 for 循环的情况下将单元格转换为矩阵
Converting a cell to matrix in the presence of a for loop
我是 运行 LASSO 估计方法和 for 循环。
代码如下:
%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]};
我知道这是一个远景,但它会有所帮助,因为上面的内容很容易输入,但如果我增加尺寸,这将成为一项非常困难的任务。
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
我是 运行 LASSO 估计方法和 for 循环。
代码如下:
%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]};
我知道这是一个远景,但它会有所帮助,因为上面的内容很容易输入,但如果我增加尺寸,这将成为一项非常困难的任务。
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