How can I get a matrix for such a for loop ? I want to create a matrix with each of the i values, because now I only get always the last value for i.
1 次查看(过去 30 天)
显示 更早的评论
I've two matrixes G and Rm and I want to regress one column of the G matrix on one column in the Rm matrix. When I made this in the down way, I see in command window the different values, but I only get as variable the last i output.
for i=1:6
fitlm(G(:,i),Rm(:,1))
fitlm(G(:,i),Rm(:,2));
fitlm(G(:,i),Rm(:,3));
fitlm(G(:,i),Rm(:,4));
fitlm(G(:,i),Rm(:,5));
fitlm(G(:,i),Rm(:,6));
fitlm(G(:,i),Rm(:,7));
end
Is there the possibility to solve this in another way function or so, to get in the end a matrix with the different variables ? If possible can I create a matrix with the regrossor coefficients ?
Thanks for help.
0 个评论
回答(1 个)
jgg
2015-12-12
编辑:jgg
2015-12-12
You have to save the output at each step. The ans variable is being overwritten. For example
C = struct();
for i=1:6
C.(strcat('R1C',num2str(i))) = fitlm(G(:,i),Rm(:,1))
C.(strcat('R2C',num2str(i))) = fitlm(G(:,i),Rm(:,2));
... (etc)
end
Would store your linear models in the elements of the structure label RiCj corresponding to the element you're using. Is this what you wanted to do?
(I notice you could also loop over the Rm variable instead of hard-coding that as well).
2 个评论
jgg
2015-12-14
编辑:jgg
2015-12-14
In order to get the coefficients, you have to extract them from the linearmodel object, which is not what your original code is doing. The fitlm function does not return a coefficient vector; it returns a linearmodel object.
However, this object contains all the relevant information you'd want. Click on it in the variable viewer to see the different statistics.
Let's assume your linear model has the same number of coefficients k. Then, you could do this as follows:
C = zeros(k,6*7);
count = 1;
for i=1:6
for j = 1:7
lm = fitlm(G(:,i),Rm(:,j));
coeffs = lm.Coefficients(:,1);
C(:,count) = table2array(coeffs);
count = count + 1;
end
end
if your models have different coefficient numbers, you'll have to adjust this a little bit.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!