如何使用Matlab平衡化学方程式将系数降到可能的最小整数

如何使用Matlab平衡化学方程式将系数降到可能的最小整数,matlab,linear-algebra,numerical-methods,chemistry,Matlab,Linear Algebra,Numerical Methods,Chemistry,我试图开发一个Matlab程序来平衡化学方程式。我能够通过解一个线性方程组来平衡它们。目前,我的输出是一个带有系数的列向量 我的问题是,我需要返回这些系数的最小整数值。例如,如果返回了[10,20,30]。我希望[1,2,3]被归还 实现这一目标的最佳方式是什么 我希望这个程序是完全自治的,一旦它被输入一个线性系统的矩阵。因此,我无法处理这些值,我需要从代码中自动执行这些操作。谢谢 % Chemical Equation in Matrix Form Chem = [1 0 0 -1 0 0 0

我试图开发一个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!

我不使用整数规划就能找到解决方案。我将非整数值转换为有理表达式,并使用内置的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)

“返回这些系数的最小整数值”的含义是什么?[10,20,30]的最小值应为10。在平衡化学方程式时,目标是找到反应两侧分子的正确“组合”,从而产生正确的比例。假设你被给予CO2+H2O→ C6H12O6+O2。我们需要找到使这个方程成立的最小整数系数。在这种情况下,答案是:6CO2+6H2O→ C6H12O6+6 O2。参考我的例子[10,20,30],我们可以把它想象成10x+20y+30z=0,其中我想要使方程成为真的最小整数系数。我可以自由划分它们,所以在这种情况下,我的答案是x+2y+3z=0。在我看来,你在做一些事情,比如整数规划。你可以看一看。感谢你的资源,这可能需要优化工具箱,我没有访问它…在你得到一个整数向量结果后,你需要计算条目的GCD,并将所有条目除以它。matlab有这样一个功能,或者你必须实现一个向量欧几里德算法,通过最小的非零分量减少向量元素(当然不减少这个分量),直到只剩下一个非零分量。