matlab - 如何使用 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!
解决方案
我能够在不使用整数编程的情况下找到解决方案。我将非整数值转换为有理表达式,并使用内置的 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)
推荐阅读
- django - 通过 https/ssl 的 Django DRF 令牌认证
- javascript - 为什么我在 HTML 网页上使用 HTTrack 或 Save All Resources 时没有生成所有元素?
- laravel-valet - 如何使用非 80 端口的代客服务器?
- excel - 如果“x”值丢失,可用代码停止正在运行的代码并执行某些操作并返回活动单元格并尝试运行第一个代码
- javascript - 如何使用 webload javascript 从 HTML 中存在的字符串中获取数字
- python - 使用有限数量的阴影将图像转换为灰度?
- c# - 如何强制 Visual Studio 针对 .Net Core 3.1 的发布版本编译项目?
- kernel - 我的无线接口似乎缓冲传入的消息并定期接收它们
- google-apps-script - 我可以使用服务帐户和模拟创建日历触发器吗?
- html - 如何使用 Lazarus 将 html 表格文件打开到(字符串)网格中?