If you want to include custom stack information in an MException object, you'll need to use a workaround. One common approach is to append the stack information to the exception message or use the addCause method to attach additional information.
To manually append the stack information to the exception message you can do something like:
% Define the stack information
myStack = struct('file', 'myFile', 'name', 'myName', 'line', 42);
% Create a formatted string with stack information
stackInfo = sprintf('Error occurred in file: %s, function: %s, line: %d', ...
myStack.file, myStack.name, myStack.line);
% Create the MException object with the stack information in the message
myEx = MException('foo:bar', 'myErrString\n%s', stackInfo);
% Display the exception
disp(getReport(myEx, 'extended'));
Or, if you want to provide additional context or a secondary exception, you can use the "addCause" method:
% Create the primary MException object
myEx = MException('foo:bar', 'myErrString');
% Create a secondary MException with stack information
causeEx = MException('foo:bar:stack', 'Stack info: %s, %s, %d', ...
myStack.file, myStack.name, myStack.line);
% Add the secondary exception as a cause
myEx = myEx.addCause(causeEx);
% Display the exception with causes
disp(getReport(myEx, 'extended'));