简体   繁体   中英

Matlab: how to run a For loop with multiple outputs?

So my question refers to the regress() function in matlab. Click here for the Matlab documentation

If I want to run multiple regressions using this function and output both the coefficients and the confidence intervals, what's the best way to do this in a For loop?

Matlab's own syntax for this is [b,bint] = regress(y,X). But when I try to implement this in a for loop it tells me that the dimension mismatch. My code is the following:

for i=1:6
[a, b]=regress(Dataset(:,i),capm_factors);
capm_coefs(i,:)=a;
capm_ci(i,:)=b;
end

Please help, thanks!

regress outputs a column vector of coefficients that minimize the least squared error between your input data ( capm_factors ) and your predicted values ( Dataset(:,i) ). However, in your for loop, you are assuming that a and b are row vectors .

Also, the first output of regress is the solution to your system, but the second output contains a matrix of confidence values where the first column denotes the lower end of the confidence interval for each variable and the second column denotes the upper end of the confidence interval.

Specifically, your input capm_factors should be a M x N matrix where M is the total number of input samples and N is the total number of features. In your code, a would thus give you a N x 1 vector and b would give you a N x 2 matrix.

If you'd like use a loop, make sure capm_coefs is a N xl matrix where l is the total number of times you want to loop and capm_ci should either be a N x 2 xl 3D matrix or perhaps a l element cell array. Either way is acceptable.... but I'll show you how to do both.

Something like this comes to mind:

Confidences as a 3D matrix

l = 6; %// Define # of trials
[M,N] = size(capm_factors); %// Get dimensions of data
capm_coefs = zeros(N, l);
capm_ci = zeros(N, 2, l);

for ii = 1 : l
    [a,b] = regress(Dataset(:,i), capm_factors);
    capm_coefs(:,ii) = a;
    capm_ci(:,:,ii) = b;
end

You'd then access the coefficients for a trial via capm_coefs(:,ii) where ii is the iteration you want. Similarly, the confidence matrix can be accessed via capm_ci(:,:,ii)

Confidences as a cell array

l = 6; %// Define # of trials
[M,N] = size(capm_factors); %// Get dimensions of data
capm_coefs = zeros(N, l);
capm_ci = cell(l); %// Cell array declaration

for ii = 1 : l
    [a,b] = regress(Dataset(:,i), capm_factors);
    capm_coefs(:,ii) = a;
    capm_ci{ii} = b; %// Assign confidences to cell array
end

Like above, you'd access the coefficients for a trial via capm_coefs(:,ii) where ii is the iteration you want. However, the confidence matrix can be accessed via capm_ci{ii} as we are now dealing with cell arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM