Как уменьшить коэффициенты до минимально возможных целых чисел, используя Matlab - Balancing Chemical Equations - PullRequest
0 голосов
/ 17 октября 2019

Я пытаюсь разработать программу 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!

1 Ответ

0 голосов
/ 18 октября 2019

Мне удалось найти решение без целочисленного программирования. Я преобразовал нецелые значения в рациональные выражения и использовал встроенную функцию 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)
...