Substitute variables without immediate evaluation
9 次查看(过去 30 天)
显示 更早的评论
I am looking for a way of automating writing parts of reports. In particular, whenever I have an equation, I'd like to write it in LaTeX in a particular form, example given:
y = sqrt(a+b) = sqrt(2+3) = 2.2361
(for a = 2, b = 3).
The trouble begins with the sqrt(2+3) part. I've been trying various methods but I can't seem to prevent MATLAB from immediately evaluating given expression. I'd like to keep it as sqrt(2+3) if possible, or just have it written in text/LaTeX form. In Mathematica, you can use the Trott-Strzeboński technique for in-place evalutation although it's a bit complicated. Is there any sensible way to do that in MATLAB?
The important thing is that I don't always know what the equation is (it's often calculated by MATLAB given other information), all I know is the variables and their values.
While one possible solution would be to use string replace to replace parts of a LaTeX equation, substituting symbolic (text) variables for their values, it would be needlessly complicated, would have to include many cases (whenever MATLAB formats a symbolic variable such as A_B as A_{B}, etc.) and prone to error. I'm looking for a simpler way, and string replace would be my last resort.
0 个评论
回答(1 个)
Vatsal
2024-5-16
编辑:Vatsal
2024-5-16
Hi,
In MATLAB, to substitute variables in an equation without immediate numerical evaluation and to format the equation for LaTeX, symbolic math toolbox can be utilized. This method enables symbolic manipulation and display of expressions, including variable substitution and conversion of symbolic expressions to LaTeX strings.
Here is a starting point on how to achieve this:
% Step 1: Define Symbolic Variables
syms a b
% Step 2: Define the Equation Symbolically
eqn = sqrt(a + b);
% Step 3: Substitute Variables Symbolically
% Example values for a and b
values = {2, 3};
eqn_sub = subs(eqn, [a, b], values);
% Step 4: Convert to LaTeX
latex_str = latex(eqn_sub); % Converts the substituted equation to LaTeX
% Step 5: Combine for Reporting
% Creates a string for reporting that includes the original equation in LaTeX,
% the substituted equation in LaTeX, and the numerical evaluation
report_str = sprintf('y = %s = %s = %f', latex(eqn), latex_str, eval(eqn_sub));
% Display the final report string
disp(report_str);
when using eval, the expression is finally evaluated to a numerical value. If you want to keep it symbolic, just omit the eval part in the reporting.
I hope this helps!
1 个评论
Steven Lord
2024-5-16
Do not use eval. This is true both numerically and symbolically. If you want to substitute values into a symbolic expression use subs instead.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!