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 view (last 30 days)
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.

Answers (1)

jgg
jgg on 12 Dec 2015
Edited: jgg on 12 Dec 2015
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 Comments
Fox
Fox on 13 Dec 2015
Hi, thanks. For the help. I wanted to have a matrix C of the Coefficients at the end. You know therefore a solution ? If I want to loop Rm , do I need an additional loop in the old one ?
jgg
jgg on 14 Dec 2015
Edited: jgg on 14 Dec 2015
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.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!