0028 1 VBA Macros and Functions
0028 1 VBA Macros and Functions
Step 4. Go back to the Excel workbook by clicking [Alt-F11] once more. Then click
[Alt-F8] to change the macro options and select shortcut key (plus add description if
desired).
Step 5. Test the macro. First prepare the spreadsheet with a matrix which will be treated
as matrix A and column of cells to be treated as vector x. Then run the macro.
Example: Writing a function that evaluates the real roots of a cubic equation
For the cubic equation:
𝑓 (𝑥 ) = 𝑎 𝑥 3 + 𝑏 𝑥 2 + 𝑐 𝑥 + 𝑑
One of the real roots can be found using Newton’s method:
[𝑘+1] [𝑘]
𝑓(𝑥 [𝑘] )
𝑥 =𝑥 − [𝑘]
𝑑𝑓/𝑑𝑥 𝑥
Where the iteration is repeated until the difference between 𝑥 [𝑘+1] and 𝑥 [𝑘] is below
a specified tolerance
After this first root, 𝑥1 , has been found, two real roots will exist if the discriminant ∆
is non-negative, where
∆= 𝛼 2 − 2𝛼 𝑥1 − 3 𝑥12 − 4𝛽
𝑏
𝛼=
𝑎
𝑐
𝛽=
𝑎
If ∆≥ 0 the other two real roots are given by
−(𝛼 + 𝑥1 ) + √∆
𝑥2 =
2
−(𝛼 + 𝑥1 ) − √∆
𝑥3 =
2
A function to implement this is given below as realCubeRoot(a,b,c,d,n).