The simulation results using the MATLAB function block and S-function block are different because the C code you have written for the S-function block is not equivalent to the code in MATLAB function block due to a small difference.
In the MATLAB function block, the ‘err’ variable is given the value of the input variable ‘ref’ after the assignment of variables ‘err_n2’and ‘err_n1’.
err_n2 = err_n1 ; %Initially Zero
err_n1 = err ; %Initially Zero because err = 0
err = ref; %The input ref is assigned to err
While in the S-function block, the equivalent variables ‘SOGI_v.vin’, ‘SOGI_v.vin_n1’, and ‘SOGI_v.vin_n2’ are handled differently. SOGI_v.vin is assigned the input variable ‘vin’ before ‘SOGI_v.vin_n1’ and ‘SOGI_v.vin_n2’ have been assigned. This makes the initial state of the variables different and hence leading to the wrong result.
SOGI_v.vin = vin; %Assigned before SOGI_v.vin_n1 and SOGI_v.vin_n2
SOGI_v.d0 = (4 + 2 * K * Ts * w + (w * w * Ts * Ts));
d0 = (4 + (2 * K * Ts * w) + (w * w * Ts * Ts));
SOGI_v.b1 = (-8 + (2 * w * w * Ts * Ts)) / SOGI_v.d0;
SOGI_v.b2 = ((4 - (2 * K * Ts * w) + (w * w * Ts * Ts))) / SOGI_v.d0;
SOGI_v.a_alpha = (2 * K * Ts * w) / SOGI_v.d0;
SOGI_v.a_beta = (K * w * w * Ts * Ts) / SOGI_v.d0;
b1 = (-8 + (2 * w * w * Ts * Ts)) / (4 + (2 * K * Ts * w) + (w * w * Ts * Ts));
b2 = ((4 - (2 * K * Ts * w) + (w * w * Ts * Ts))) / (4 + (2 * K * Ts * w) + (w * w * Ts * Ts));
a1 = (2 * K * Ts * w) / (4 + (2 * K * Ts * w) + (w * w * Ts * Ts));
SOGI_v.vin_n2 = SOGI_v.vin_n1; %Initially zero
SOGI_v.vin_n1 = SOGI_v.vin; %Not initially zero as vin is already assigned
To fix the issue, just write the assignment of ‘SOGI_v.vin’ after assigning ‘SOGI_v.vin_n2’ and ‘SOGI_v.vin_n1’ and it should give the correct result.