Untitled

 avatar
unknown
matlab
2 months ago
2.8 kB
3
Indexable
syms x y C

    % Define M(x, y) and N(x, y)
    M = x^2 + y;
    N = x- 2*y;

    % Compute partial derivatives
    dM_dy = diff(M, y); % ∂M/∂y
    dN_dx = diff(N, x); % ∂N/∂x

    % Check for exactness
    if simplify(dM_dy - dN_dx) == 0
        fprintf('The given differential equation is exact.\n');

        % Solve for the potential function F(x, y)
        F_x = int(M, x);  % Integrate M with respect to x
        F_y = int(N, y);  % Integrate N with respect to y

        % Convert symbolic results to strings for comparison
        f2_content = char(F_x);
        f3_content = char(F_y);

        % Compare the lengths of the function definitions
        if length(f2_content) > length(f3_content)
            F = F_x;
        else
            F = F_y;
        end

        % Display the general solution F(x, y) = C
        fprintf('General solution:\n');
        disp(F == C);

    else
        fprintf('The given differential equation is NOT exact.\n');

        % Finding an integrating factor 
        f_1 = simplify((dM_dy - dN_dx)/N);
        f_2 = simplify(-(dM_dy - dN_dx)/M);
        vars_1 = symvar(f_1);
        vars_2 = symvar(f_2);
        dependency =0;
        if ismember(sym('x'), vars_1) && ~ismember(sym('y'), vars_1)
            dependency = 0;         %depends only on x
        elseif ismember(sym('y'), vars_2) && ~ismember(sym('x'), vars_2)
            dependency = 1;
        else
            dependency = 2;
        end
        if dependency == 2 %depends only on y
            mu = exp(int(f_2, y));
        elseif dependency ==0 % Depends only on x
            mu = exp(int(f_1, x));
        
        end
        
        M_new = simplify(mu * M);
        N_new = simplify(mu * N);

        % Check if the new equation is exact
        dM_dy_new = simplify(diff(M_new, y));
        dN_dx_new = simplify(diff(N_new, x));

        if simplify(dM_dy_new - dN_dx_new) == 0
            disp(['mu = ', char(mu)]);
            fprintf('Now the given differential equation is exact.\n');
            
            
            % Solve for the potential function F(x, y)
            F_x_2 = int(M_new, x);
            F_y_2 = int(N_new, y);

            % Convert symbolic results to strings for comparison
            f4_content = char(F_x_2);
            f5_content = char(F_y_2);

            % Compare the lengths of the function definitions
            if length(f4_content) > length(f5_content)
                F = F_x_2;
            else
                F = F_y_2;
            end

            % Display the general solution F(x, y) = C
            fprintf('General solution:\n');
            disp(F == C);
        else
            fprintf('S.et knk\n');
        end
    end

Editor is loading...
Leave a Comment