Custom Display for symbolic Object

10 views (last 30 days)
Justin Ferland
Justin Ferland on 20 Apr 2024
Answered: Shishir Reddy on 24 Dec 2024 at 4:33
Hello,
I do alot of work with symbolic variables and latex, and I would like to have some custom output for when a semi colon is not put at the end of a line, I would like it to output the formated version of the symbolic variable so that I can use the copy as LaTeX. An example of how I would like it displayed is below, when I run the line sigma_i = 10*u.MPa I would like it to be displayed as if I had run myFunc.
u =symunit;
sigma_i =10*u.MPa
sigma_i = 
myFunc(sigma_i)
function myFunc(inputValue)
varName = inputname(1);
symbolicVarName = sym(varName);
disp(vpa(symbolicVarName == inputValue, 3)); % Adjust the precision as needed
end
I have tried creating class MySym which inherits from sym but whenever I do any operations the output ends up being a sym
classdef MySym < sym
methods
% Constructor method
function obj = MySym(val)
% Convert input to sym and store it in the object
obj = obj@sym(val); % Call superclass constructor
end
% Custom display method
function display(obj)
varName = inputname(1);
if isempty(varName)
varName = 'ans';
end
symbolicVarName = sym(varName);
disp(vpa(symbolicVarName == obj, 3)); % Display with 3 digits precision
end
end
end

Answers (1)

Shishir Reddy
Shishir Reddy on 24 Dec 2024 at 4:33
Hi Justin
To achieve the behavior where a symbolic variable automatically displays its formatted LaTeX representation when a semicolon is omitted, a custom class can indeed be created that extends sym. However, to ensure that operations on instances of the new class return instances of the same class (rather than reverting to sym), the arithmetic operations and other relevant methods has to be overidden.
The following methods could be incorporated in the MySym class to ensure the output doesn't end up being a sym.
% Override arithmetic operations to return MySym objects
function result = plus(a, b)
result = MySym(plus@sym(a, b));
end
function result = minus(a, b)
result = MySym(minus@sym(a, b));
end
function result = mtimes(a, b)
result = MySym(mtimes@sym(a, b));
end
function result = mrdivide(a, b)
result = MySym(mrdivide@sym(a, b));
end
function result = mpower(a, b)
result = MySym(mpower@sym(a, b));
end
Similarly, more methods can be added as per requirement.
This setup should ensure that any operations involving MySym instances return results that are also MySym instances, allowing for consistent behavior across all the calculations.
For more information regarding sym, kindly refer the following documentation -
I hope this resolves the issue.

Products


Release

R2024a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!