Aproximate roots using Bairstow method

7 views (last 30 days)
Hello guys.
I have a code in c++, which implement the Bairstow method, but I don't know how to convert it in Matlab.
Can anyone help me with some tips ? I know it is a code on this webside, which makes the same thing, but I don't understand it very well.
This is the code :
#include <iostream>
#include <math.h>
#include <stdlib.h>
using namespace std;
double a, p0, q0, b, c, delta, P, Q, R, S, eps;
int n, i;
double max(double a, double b) {
if (a >= b)
return a;
else
return b;
}
void rezolv_ec2(double a, double b, double c) {
double d, x1, x2;
d = b * b - 4 * a*c;
if (d >= 0) {
cout << "\n" << (-b - sqrt(d)) / (2 - a) << endl;
cout << "\n" << (-b + sqrt(d)) / (2 - a) << endl;
}
if (d < 0) {
cout << "\n" << -b / (2 * a) << "-i*" << sqrt(-d) / (2 * a);
cout << "\n" << -b / (2 * a) << "+i*" << sqrt(-d) / (2 * a);
}
}
void rezolv_ec1(double a, double b) {
cout << "\n" << -b / a << endl;
}
void main() {
cout << "Dati gradul ec.="; cin >> n;
for (i = 0; i <= n; i++) {
cout << "a[" << i << "]="; cin >> a[i];
}
do {
cout << "\np0="; cin >> p0;
cout << "\nq0="; cin >> q0;
cout << "\nDati eroarea admisa eps="; cin >> eps;
do {
b = a;
b = a - p0 * b;
for (i = 2; i <= n; i++) {
b[i] = a[i] - p0 * b[i - 1] - q0 * b[i - 2];
}
c = b;
c = b - p0 * c;
for (i = 2; i <= n - 1; i++) {
c[i] = b[i] - p0 * c[i - 1] - q0 * c[i - 2];
}
delta = pow(c[n - 2], 2) - c[n - 3] * c[n - 1] + c[n - 3] * b[n - 1];
P = -b[n - 1] * c[n - 2] + b[n] * c[n - 3];
Q = -b[n] * c[n - 2] + b[n - 1] * c[n - 1] - pow(b[n - 1], 2);
p0 -= P / delta;
q0 -= Q / delta;
R = b[n - 1];
S = b[n] + p0 * b[n - 1];
} while (max(fabs(R), fabs(S)) > eps);
rezolv_ec2(1, p0, q0);
n = n - 2;
for (i = 0; i <= n; i++) {
a[i] = b[i];
}
} while (n >= 3);
if (n == 2)
rezolv_ec2(b, b, b);
if (n == 1)
rezolv_ec1(b, b);
}

Sai Sri Pathuri on 9 Jul 2020
You may use the following resources
1. Declare function name, inputs, and outputs - https://in.mathworks.com/help/matlab/ref/function.html
2. if, elseif, else Documentation - https://in.mathworks.com/help/matlab/ref/if.html
3. Display text in the Command Window - disp or fprintf
4. Loops - for and while