You usually get lost data back in MATLAB by recovering the source rather than the variable: reopen the last saved copy (.mat, .mlx, script, or app session), then reconstruct unsaved work from the Command Window history, diary logs, autosave files, and recycled .mat backups. If the file was deleted, restore it from the Recycle Bin, trash, a cloud version history, or your backup. MATLAB has no built-in “undelete” command for arbitrary numbers that vanished from memory, and nothing can be promised after a crash — so the answer depends heavily on which kind of loss you had.
The rest of this guide walks through each failure mode in order, from the fastest reversible checks to the reconstruction work that takes longer. Along the way you'll see how MATLAB actually stores data, which is what makes some recoveries trivial and others impossible.
First, Identify What "Lost" Actually Means
"Lost data" in MATLAB covers at least five different situations, and each has a different recovery path:
A variable disappeared or was overwritten in the workspace during the current session. A .mat file was deleted, moved, or corrupted. A live script or function file was unsaved or overwritten (.m, .mlx). The session crashed or MATLAB closed, taking unsaved work with it. The filesystem or a drive failed, or a cloud-sync conflict replaced a file.
Before touching anything, stop writing to the affected location. If a file was deleted from a drive, every new save, download, or MATLAB autosave to that drive reduces the chance a file-recovery utility can find the old blocks. The same caution applies to overwritten .mat files: the old bytes may still be recoverable with a file-level tool only if nothing has reused that disk space.
A quick way to narrow the case is to ask three questions. Was the data ever saved to disk? If yes, where (working folder, a project folder, a cloud-sync folder)? And is the loss a missing file, a corrupted file, or missing numbers inside an existing session? The answers determine which section below applies.
Recover Variables That Vanished During a Session
When a variable disappears mid-session, the cause is usually one of a few specific things, and MATLAB leaves a trail for most of them.
Start with the Command History. The Command Window history records commands you typed, not their output, but it preserves the expressions that generated data. If you built a variable with a line like results = arrayfun(@simulate, params);, you can rerun that line as long as the inputs still exist or can be regenerated. The History window (or history at the prompt, depending on version) lets you search, copy, and rerun prior commands. On recent releases the history persists across sessions, so it can also help after a restart.
Check for accidental clearing. clear removes all variables; clear x removes just x; clearvars -except keepMe removes everything else. If a script starts with clear all, running it wipes the workspace before doing anything. If that is what happened, the variables are gone from memory and must be rebuilt from saved files or history. A practical fix for the future is to avoid clear all in scripts and use functions with their own local workspaces instead.
Check for overwriting. A variable overwritten by a later assignment cannot be rolled back, but you may still find its earlier state if it was saved or displayed. Look for disp, fprintf, or save calls in your history that captured the prior value.
Check the workspace browser and whos. A large variable may still be there but hidden by a filter, or you may be looking at the wrong workspace. whos lists variables in the base workspace; inside a function, the local workspace is separate. If you ran code as a function or through a parfor loop, intermediate values may never have existed in the base workspace at all.
Check for scope problems. A common report is “my variable is empty after the loop.” Often the variable was created inside a function or a nested scope and never returned. The data was never lost; it simply was not assigned to an output. Editing the function to return it, or using assignin('base', ...) deliberately, fixes the pattern.
Success check: after rerunning history commands or restoring from a save, run whos and compare the variable's class, size, and a checksum-like summary (for example, sum or max of a numeric array) against what you remember. If those match, you have the right data back.
Recover Deleted or Damaged MAT-Files
.mat files are the standard MATLAB container for saved workspaces. Recovery depends on how the file was lost.
Deleted file. Check the operating system's Recycle Bin or Trash first. On Windows, the Recycle Bin also holds files deleted from some network locations depending on configuration. On macOS, check Trash. If you use a cloud-synced folder (OneDrive, Dropbox, Google Drive, iCloud Drive), open the service's version history or “restore” view — most retain deleted files for a limited window that varies by plan and provider, so check promptly.
File moved or renamed. Search the whole drive by extension and by a distinctive variable name you remember. On Windows, dir /s /b .mat from a command prompt, or the File Explorer search, works; on macOS or Linux, find ~ -name ".mat" is the equivalent. MATLAB's dir and what functions list files in the current folder, and which -all helps locate files on the path.
Corrupted file. A truncated or damaged .mat may fail to load with an error. Try load with output capture to see whether partial data survives:
If the file uses the v7.3 (HDF5-based) format, HDF5 tools may still read intact datasets even when MATLAB's loader complains; h5disp and h5read can inspect and extract them. For older v7 and earlier formats, partial recovery is much harder and a file-repair utility is the practical route. If the file came from a network drive or cloud sync, a truncated copy is common — re-download or restore an earlier version.
A caveat on .mat versions. Files saved with -v7.3 support variables larger than 2 GB and use HDF5; older formats do not. This matters for recovery because HDF5-structured damage is sometimes partially readable, while a corrupt header in a v7 file often blocks the whole load. Check the version with matfile behavior or the save options you used.
Success check: after loading, verify that the expected variable names are present (fieldnames on the loaded struct), sizes match, and a few known values are correct. A load that “succeeds” but returns empty or garbled arrays means the file is damaged, not recovered.
Unsaved and Overwritten Scripts and Live Scripts
Code files are a different recovery problem: the loss is text, and MATLAB's editor keeps some history.
Unsaved script in an open editor. If MATLAB is still open, check whether the editor tab still exists. If MATLAB crashed, look for autosave and recovery files. Recent MATLAB versions store autosave data for the editor, and on restart the editor may offer to restore unsaved changes. Look in the editor's recovery prompts and in the autosave location your installation uses; the exact folder varies by version and platform, so check MATLAB's preferences (Editor/Debugger settings) rather than assuming a path.
Overwritten file. If you saved over a good file with a bad one, check the operating system's previous-versions feature (Windows File History or restore points), macOS Time Machine local snapshots, or the cloud provider's version history. Version history is usually the fastest and most reliable route when the file lives in a synced folder.
Deleted file. Same as .mat: Recycle Bin or Trash first, then cloud version history, then backups. A file-recovery utility is a last resort and works best before the disk has been written to.
Publishable live scripts. Live scripts (.mlx) are zip-based packages; a damaged .mlx can sometimes be opened as an archive and its internal XML recovered. That is advanced repair, not routine recovery, and it should be attempted on a copy.
Success check: open the recovered file, run it, and confirm output matches expectations. Compare with any earlier copy you can find; a diff tool or visdiff in MATLAB highlights differences.
Reconstructing Work After a Crash or Lost Session
If MATLAB closed and unsaved variables are gone, the memory state is gone with it. Recovery now means rebuilding from traces.
Command history is the primary trace. Rerun the commands that generated the data, in order. If your workflow was scripted, this is fast; if it was interactive, expect to replay many lines. Batch the replay by copying history into a script, then running it once.
Diary logs. If diary was active — diary('session.log') — the log captures printed output, including displayed arrays. That does not restore variables, but it can recover printed values you need to re-enter. diary off ends logging.
Saved checkpoints. Look for any .mat files created by save calls in your history. Even a partial checkpoint (save('checkpoint.mat', 'x', 'y')) preserves those variables. Restore with load.
Reproducibility practices that reduce future loss. Save intermediate results at meaningful milestones rather than only at the end. Use save with explicit variable lists so a later clear cannot affect what is stored. Keep scripts in version control so code — and the parameters that generate data — are never only in memory. For long computations, write results to disk inside the loop.
A worked illustration: suppose a two-hour simulation stored only its final results variable in memory, and MATLAB crashed. If the script that ran the simulation is on disk with its parameters, rerunning it regenerates the data exactly (assuming deterministic code). If the parameters were typed interactively and only partly appear in history, you may recover most but not all of them — which is why explicit parameter files are worth the small effort.
Success check: after reconstruction, compare against any surviving printed output or checkpoint. If no reference survives, document the assumptions used to rebuild.
Use MATLAB's Saving Features as a Recovery Net
The best recovery is the one you set up beforehand, and MATLAB offers several low-cost nets.
save with checkpoints. save('work.mat') stores the entire workspace; save('work.mat', 'a', 'b') stores selected variables. Saving at milestones creates multiple recovery points instead of one.
matfile for partial saves. matfile lets you write parts of a large array without loading the whole thing, which makes frequent checkpointing of big data practical. It also allows reading subsets after a crash without loading everything.
diary for printed evidence. Turning on diary at the start of a session costs nothing and captures printed arrays and messages that would otherwise vanish. It is not a substitute for saving variables, but it is a genuine last-resort trace.
Version control for code. Git or another system means an overwritten script can be restored from a commit. Even without a remote server, a local repository with frequent commits is a real safety net.
Cloud-synced project folders. Synced folders give you version history and trash retention from the provider. The retention window varies by service and plan; confirm it for your account rather than assuming indefinite recovery.
Autosave settings. Confirm the editor's autosave interval in preferences, and know where recovery files go on your platform and version, since this differs across releases.
Success check: deliberately test the net once — save a checkpoint, close MATLAB without saving, reopen, and load the checkpoint. A recovery plan you have never exercised is a plan you do not know works.
When the Data Cannot Be Recovered
Some losses are final. Variables cleared from memory without a save are gone; there is no hidden cache MATLAB exposes. A .mat file overwritten and then had its disk space reused by new writes is likely unrecoverable. A crashed session with no saved checkpoint and no history leaves nothing to replay.
In these cases, the honest path is reconstruction from knowledge: re-derive the data from the code and parameters, re-collect measurements if they came from an external instrument, or accept the loss and rebuild. A file-recovery utility can help for deleted files on a drive that has not been written to, but it cannot help for in-memory variables, and no MATLAB command restores them.
A stop condition worth naming: if the lost data came from a failed drive that is making unusual noises, stop using it and seek professional data-recovery help rather than running utilities yourself, which can worsen physical damage. Similarly, if the file lives on a managed corporate or institutional system, contact your IT administrator before trying recovery tools; their backup and retention policies may already hold a copy, and unauthorized recovery attempts can conflict with them.
Practical Prevention Checklist
The recovery steps above work best in combination with habits that make future losses small:
Save checkpoints at milestones with explicit variable lists. Keep code in version control and commit before risky edits. Turn on diary for sessions where printed output matters. Place projects in cloud-synced folders with known version-history retention. Confirm editor autosave and recovery settings for your MATLAB version. Test one restore path once so you know it works. Avoid clear all at the top of scripts; use functions instead.
None of these guarantee recovery, but together they turn most “lost data” events into minor inconveniences rather than disasters. The common thread is that MATLAB's recovery options are strongest for data that touched disk — a saved file, a printed diary line, a committed script — and weakest for data that lived only in memory.