Mathematica Asked by Wai-Ga D Ho on May 27, 2021
I was a bit curious if anyone knows of any compact way to use Set and/or SetDelayed if we want to, say, generate Fit functions and index them as well.
To demonstrate what I had in mind, consider the following data set for a minimal working example:
data = { {{1, 2}, {2, 4}, {3, 6}} , {{1, 1}, {2, 2}, {3, 3}} };
Now it’s apparent that fitting data[[1]]
and data[[2]]
should provide the functions f[x]=2x and f[x]=x, respectively. But I was hoping to combine Set (=)
and/or SetDelayed (:=)
in the simplest manner, so that I may define a single compact function that can provide both the fit functions and the numerics for each fit.
Defining
fitdata[i_, x_] := Fit[data[[i]], {1, x}, x]
works at the indexing level, where I can input a value for i
and evaluate fitdata[1,x]
and fitdata[2,x]
to return either functional dependences on x. However, trying to input a value for both i
and x
yields an error, and I was wondering if anyone knows the easiest way to define a function that can both return the i
th Fit function AND return a number corresponding to an input x
for this function.
I’m aware that there are a number of simple ways we can both index a set of Fit functions and obtain numerical values of the fit, including but not limited to:
x
argument for the desired elementx
-dependence of the function and using a rule to cast an x
-value for fitdata[i_] := Fit[data[[i]], {1, x}, x]
.However, I’d like to avoid adding rules or defining new variables if I can, since I’m worried my code will get a bit messy or over-complicated whenever I start iterating over these functions to calculate things here or make some plots there, etc.
The function that I had in mind above would probably be the cleanest way for me to implement things, so I was just wondering if anyone knows of a way that some fit_data[i,x]
can be defined to act in this manner I originally envisioned. I suspect there may be some way to use Set and/or SetDelay so that the expression is evaluated in the way that I hope, but I am not sure.
I tried looking some solutions up on the forum but most answers were a bit more complicated than the alternatives I laid out above, or they discussed memoization which doesn’t seem to be necessary in the case I’ve described here.
You could use LinearModelFit
(or NonlinearModelFit
according to your needs):
Clear[fitn]
fitn[dataset_, i_] := LinearModelFit[dataset[[i]], {1, x}, x]
fitn[data, 2]
(* Out: FittedModel[0. + 1. x] *)
When you want a specific calculated value, you can use:
fitn[data, 1][2.5]
(* Out: 5. *)
Correct answer by MarcoB on May 27, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP