首页 > 解决方案 > 如何使用 Matlab 将系数减少到可能的最低整数 - 平衡化学方程式

问题描述

我正在尝试开发一个 Matlab 程序来平衡化学方程式。我能够通过求解线性方程组来平衡它们。目前我的输出是一个带有系数的列向量。

我的问题是我需要返回这些系数的最小整数值。例如,如果返回 [10, 20, 30]。我希望返回 [1, 2, 3]。

实现这一目标的最佳方法是什么?

我希望这个程序在输入带有线性系统的矩阵后完全自主。因此我无法使用这些值,我需要从代码中自动执行此操作。谢谢!

% Chemical Equation in Matrix Form
Chem = [1 0 0 -1 0 0 0; 1 0 1 0 0 -3 0; 0 2 0 0 -1 0 0; 0 10 0 0 0 -1 0; 0 35 4 -4 0 12 1; 0 0 2 -1 -3 0 2]

%set x4 = 1 then Chem(:, 4) = b and 
b = Chem(:, 4);     % Arbitrarily set x4 = 1 and set its column equal to b
Chem(:,4) = []      % Delete the x4 column from Chem and shift over
g = 1;              % Initialize variable for LCM 
x = Chem\b          % This is equivalent to the reduced row echelon form of 
                    % Chem | b

% Below is my sad attempt at factoring the values, I divide by the smallest decimal to raise all the values to numbers greater than or equal to 1
for n = 1:numel(x)
   g = x(n)*g
    M = -min(abs(x))
    y = x./M
end


I want code that will take some vector with coefficients, and return an equivalent coefficient vector with the lowest possible integer coefficients. Thanks!

标签: matlablinear-algebranumerical-methodschemistry

解决方案


我能够在不使用整数编程的情况下找到解决方案。我将非整数值转换为有理表达式,并使用内置的 matlab 函数来提取每个表达式的分母。然后,我使用内置的 matlab 函数来查找这些值的最小公倍数。最后,我用矩阵乘以最小公倍数来找到我的答案系数。

    % Chemical Equation in Matrix Form
clear, clc
% Enter chemical equation as a linear system in matrix form as Chem
Chem = [1 0 0 -1 0 0 0; 1 0 1 0 0 -3 0; 0 2 0 0 -1 0 0; 0 10 0 0 0 -1 0; 0 35 4 -4 0 -12 -1; 0 0 2 -1 -3 0 -2];
% row reduce the system
C = rref(Chem);
% parametrize the system by setting the last variable xend (e.g. x7) = 1
x = [C(:,end);1];
% extract numerator and denominator from the rational expressions of these
% values
[N,D] = rat(x);

% take the least common multiple of the first pair, set this to the
% variable least
least = lcm(D(1),D(2));

% loop through taking the lcm of the previous values with the next value
% through x
for n = 3:numel(x)
  least = lcm(least,D(n));
end

% give answer as column vector with the coefficients (now factored to their
% lowest possible integers
coeff = abs(least.*x)

推荐阅读