Convert/decompose formula terms similarly to LinearModel

조회 수: 1(최근 30일)
I'm trying to do something which must be implicitly done inside LinearModel.predict(), but I can't seem to get to it.
The task I'm trying to do is to have a linear formula given as a set of terms:
formulaTerms = {'X1','X2','X1*X2'} % ie, y = X1 + X2 + X1*X2
and then have the input terms defined in their simplest state such as:
inputTerms = {'X1','X2'}
and then produce a function that will take in each term in inputTerms and return to me each term in formulaTerms. For example in this instance the result would be:
outFcn = @(input)[input(1), input(2), input(1)*input(2)]
outFcn([2 3]) % Which gets the 3 terms in the formula: [2 3 6]
What I'm trying to do is generalise this to a function such as:
function linearFcn = convert(formulaTerms, inputTerms)
% linearFcn = ... (well, this is what I'm trying to write!)
The closest I can get to a general solution is something like the following where I can convert my formulaTerms into a formula string similar to what accepts:
f = classreg.regr.LinearFormula('y ~ X1 + X2 + X1*X2',{'y','X1','X2'},'',[],'identity')
This is basically what is created inside the LinearModel object, but I don't know how LinearModel.predict(input) combines this input variable with the LinearFormula object to produce the actual terms that are summed up to complete the linear model prediction.

채택된 답변

Shashank Prasanna
Shashank Prasanna 2013년 5월 3일
편집: Shashank Prasanna 2013년 5월 3일
Sven, what you are interested in is the designmatrix: x2fx
Alternatively, if you are still interested in the what predict does:
mdl =,y)
formulaTerms=classreg.regr.modelutils.designmatrix([X ones(length(X),1)],...
  댓글 수: 1
Sven 2013년 5월 5일
Aha... nice one Shashank, I'd found a designmatrix being built inside the LinearFunction object, but x2fx is indeed more suitable (and accessible). Thanks.

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

추가 답변(0개)

Community Treasure Hunt

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

Start Hunting!

Translated by