You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
    Metadata details:
    filename: varMicro.m
    path of file: ./repos/Microstate-EEGlab-toolbox/Microstate1.0
    
    the code of the file until where you have to start completion: function [A_opt,L_opt,Res] = varMicro(X,K_range,opts)
    
function F = free_energy(Z,sig2,sig2_0,S,beta,C,N,K)
% Calculate free energy of solution. beta needs to be last variable
% calculated.
F1 = -0.5*(N*K*log(2*pi)+sum(sum(log(sig2)))) -N*K/2 + sum(sum(S.*log(S)));
F2 = 0.5*K*N*log(2*pi*sig2_0) + sum(sum(Z.^2+sig2))/(2*sig2_0) + N*log(K);
F3 = -C*N/2*log(beta/(2*pi)) + C*N/2; % using expression for beta in last part

F = F1+F2+F3;
if isnan(F), error('hov'), end