Setting Z Offset Automatically on Startup

Hello there,
I have an old-style proximity sensor, and as you know, these sensors are affected by temperature. Every time I turn on the printer, I have to adjust the Z offset according to the ambient temperature I get from the table.
What I want to do is to run an algorithm like this in the boot using the Gcode script or some other way:

//Get the ambient temperature from bed sensor
T = X celcius
//Do some empirical calculations
Zheight = -0.85 - (1/T)*100
//Send it to the printer
M851 Z [Zheight]

I hope I could explain my problem. thanks for your help in advance.