Files
nappMATLAB-toolbox/utils/nappSaveDataTable.m
T

70 lines
2.5 KiB
Matlab

function saveFilename = nappSaveDataTable(DataTable, options)
% NAPPSAVEDATATABLE Automatically saves the data table with a dynamic filename.
%
% NAPPSAVEDATATABLE(DataTable) saves the provided table into a .mat file.
% The filename is automatically generated based on the script or Live
% Script that called this function (e.g., "myScript_FileList.mat").
%
% The variable inside the .mat file will keep the exact same name it had
% in your workspace (e.g., if you pass 'FileList', it saves as 'FileList').
%
% Name-Value arguments:
% suffix - Text to append to the script name (default: nothing)
arguments
DataTable table
% Name-Value arguments
options.suffix char = ""
end
currentScriptName = '';
% 1. Determine the name of the script that CALLED this function
stackInfo = dbstack;
if length(stackInfo) > 1
% stackInfo(1) is nappSaveDataTable, stackInfo(2) is the caller
[~, currentScriptName, ~] = fileparts(stackInfo(2).file);
% INTERCEPT LIVE EDITOR: If it's a hidden temporary evaluation file,
% clear the name so we force it to use the fallback below.
if contains(currentScriptName, 'LiveEditorEvaluationHelper')
currentScriptName = '';
end
end
% 2. Fallback if run from the command window or intercepted from the Live Editor
if isempty(currentScriptName)
try
% Ask the MATLAB editor for the actual name of the currently open tab
[~, currentScriptName, ~] = fileparts(matlab.desktop.editor.getActiveFilename);
catch
currentScriptName = 'ManualRun';
end
end
% Ensure we have a valid string (just in case the editor is closed)
if isempty(currentScriptName)
currentScriptName = 'WorkspaceData';
end
% 3. Generate the final filename
saveFilename = sprintf('%s%s.mat', currentScriptName, options.suffix);
% 4. Determine the original variable name passed by the user (e.g., "FileList")
originalVarName = inputname(1);
% If it has no workspace name, default to 'DataTable'
if isempty(originalVarName)
originalVarName = 'DataTable';
end
% 5. Create a local variable with that exact name so the .mat file stores it correctly
eval(sprintf('%s = DataTable;', originalVarName));
% 6. Save the specific variable to the file
save(saveFilename, originalVarName);
% 7. Print confirmation
fprintf('✅ Successfully saved %s to: %s\n', originalVarName, saveFilename);
end