필터 지우기
필터 지우기

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.

조회 수: 2 (최근 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.

답변 (1개)

jgg
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
Fox
Fox 2015년 12월 13일
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 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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Regression에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by