Convert/decompose formula terms similarly to LinearModel

2 visualizaciones (últimos 30 días)
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!)
end
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 LinearModel.fit() 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.

Respuesta aceptada

Shashank Prasanna
Shashank Prasanna el 3 de Mayo de 2013
Editada: Shashank Prasanna el 3 de Mayo de 2013
Sven, what you are interested in is the designmatrix: x2fx
Alternatively, if you are still interested in the what predict does:
mdl = LinearModel.fit(X,y)
formulaTerms=classreg.regr.modelutils.designmatrix([X ones(length(X),1)],...
'Model',mdl.Formula.Terms);
  1 comentario
Sven
Sven el 5 de Mayo de 2013
Aha... nice one Shashank, I'd found a designmatrix being built inside the LinearFunction object, but x2fx is indeed more suitable (and accessible). Thanks.

Iniciar sesión para comentar.

Más respuestas (0)

Community Treasure Hunt

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

Start Hunting!

Translated by