To delete variables in MATLAB, use the clear command. Typing clear x removes just the variable x; typing clear by itself deletes every variable in the current workspace. The key condition is scope: clear acts on the workspace you're currently in—the base workspace at the command prompt, or a function's local workspace while that function runs—so the exact name and context determine what actually disappears. Related commands handle different jobs: clearvars offers filtered bulk deletion, and clearvars -except keeps a short list while wiping the rest. Understanding those differences prevents both accidental data loss and the frustrating case where a variable appears deleted but memory hasn't been released.

Below, the mechanics, ordering, and failure modes are laid out step by step, from single-name deletion to clearing entire functions and classes.

The Basic Commands and What They Actually Touch

MATLAB has two workhorses for removing variables: clear and clearvars. They overlap but aren't identical.

clear name removes the variable name from the current workspace. clear with no arguments removes all variables from the current workspace. clearvars removes all variables from the current workspace and, by default, also frees their memory more aggressively than plain clear; it also refuses to touch global variables unless you explicitly allow it. clearvars name removes specific variables by name. clearvars -except keep1 keep2 removes everything except the listed names.

The practical distinction matters. Plain clear is fast and universally supported. clearvars was introduced to give more control—pattern matching with wildcards, exclusion lists, and options that affect memory release and global variables. If you're writing code that others will run on older releases, clear is the safer baseline; modern MATLAB (R2011b and later) supports clearvars fully.

One habit worth forming: at the command prompt, type whos before and after clearing. whos lists every variable with its size, class, and bytes, so you can confirm exactly what left the workspace. who lists just the names, which is quicker but less informative.

Deleting One Variable or Several by Name

The narrowest action is removing a single named variable. At the command prompt:

1: Confirm the variable exists by typing who or whos. 2: Type clear varname and press Enter. Substitute the actual name, which is case-sensitive—Clear Data won't touch data. 3: Verify with whos that the name is gone.

To remove several at once, list them in one call: clear x y z. This is equivalent to three separate clear calls but easier to read. If any of the names doesn't exist, MATLAB doesn't error; it simply ignores the missing name and reports nothing. That silence is convenient but also a trap—if you mistype clear temprature, you'll get no warning and the real temperature stays put. Check spelling or verify with whos afterward.

For a variable whose name you store in a string, use the function form: clear('varname'). The parentheses force MATLAB to treat the argument as a function call rather than command syntax. That form becomes essential inside scripts where you build names programmatically. Note the subtlety: clear varname (command syntax, no quotes) clears the variable literally named varname, while clear('varname') clears the variable whose name is the contents of the string. Getting this backwards is a classic source of "I cleared it but it's still there."

Wiping the Whole Workspace and Releasing Memory

clear with no arguments empties the current workspace of all variables. At the command prompt, that means your entire base workspace goes blank. There's no undo dialog and no confirmation prompt. If the data took an hour to load, it's gone, so save first if there's any doubt (more on that later).

Does clear free the RAM? Partially. For most numeric and character arrays, clear removes the references and lets MATLAB's memory manager reclaim the space, but the operating system may not immediately show the freed memory. Large arrays, especially those involved in memory-mapped files, persistent variables, or handles to graphics objects, can behave differently. clearvars exists largely because it is more thorough and predictable in releasing memory and because it gives you options for controlling what gets swept.

If you truly need to reclaim memory aggressively after clearing, calling pack historically defragmented the workspace, though its benefit has diminished in modern memory management and it can be slow. For most users, clear or clearvars followed by ordinary continued work is sufficient; checking memory shows how much is available to MATLAB without necessarily proving the OS has taken the pages back.

A safer variant before a big deletion is the -except flag:

clearvars -except config results removes everything except config and results. clear -except config does the same with the older command.

This pattern shines when you've loaded fresh data and want to purge prior clutter while preserving a handful of settings or accumulated outputs.

The Scope Trap: Base Workspace vs. Function Workspace

The single most common confusion is that clear inside a function does not clear the base workspace. It clears the function's own local workspace. If you run clear in a script or function and then return to the command prompt to find your variables intact, nothing is broken—you cleared a different room than you were looking at.

The reverse also happens. Running clear all at the command prompt removes the base workspace's variables, but any persistent variables inside functions may survive depending on how they were declared, because persistent storage is separate from the base workspace. To purge persistent variables, you must clear the function that owns them: clear myFunction resets the persistent state that myFunction holds. This is a common debugging step when a function's cached state gives stale results.

For MEX files, clear mex unloads all MEX functions from memory—useful when you've recompiled a MEX file and MATLAB still runs the old binary. Similarly, clear functions removes all compiled function definitions from memory, forcing MATLAB to recompile and pick up edits. These are surgical tools, not everyday commands.

Clearing Classes, Functions, and MEX Files

MATLAB's clear reaches beyond variables:

clear classes removes all class definitions from memory, forcing redefinition on next use. Use this after editing a class definition file, since MATLAB caches class definitions and otherwise may run the old code. clear functionName clears the specified function from memory, along with any persistent variables it owns. clear functions clears all functions. clear mex unloads MEX files. clear all is a broad sweep that clears variables, functions, MEX files, and classes—effectively a near-total reset of the MATLAB session's in-memory state, though it does not restart the application.

Because clear all is so sweeping, its indiscriminate use in scripts is discouraged. It can wipe state that other parts of a project expect to persist, and it slows things down by forcing recompilation. Reserve it for deliberate reset points—typically at the top of a script you want to start from a clean slate, with eyes open about the consequences.

clear all also doesn't do what many people assume: it doesn't reset preferences, close figures, or clear the command window. The command clc clears the command window display; close all closes figures. Someone wanting a full "factory fresh" visual reset needs all three, and the figures and command history are separate concerns from variables entirely.

A Workable Sequence for Common Scenarios

Different goals call for different orderings. Here are three routines that cover most everyday needs.

Before running a fresh analysis script: Save anything worth keeping (save session.mat), then clearvars -except cfg, then run the script. The exclusion preserves your configuration while guaranteeing no stale variables bleed in. Success check: whos should show only cfg.

While debugging inside a function: At a breakpoint or in the function's own code, use clear tempBuffer to drop an intermediate array that's no longer needed. Because this acts on the local workspace, your base workspace is untouched. Verify by inspecting whos inside the function scope.

Freeing memory after loading a huge dataset: After you've extracted what you need, run clearvars bigRawData, then call whos to confirm it's gone and memory to see how much MATLAB reports as available. If memory pressure persists, consider whether other references—a handle stored in a GUI, a persistent variable—are still holding the data alive despite the name being removed.

In each case the pattern is the same: know which workspace you're in, clear the narrowest thing that solves the problem, then verify. The verification step is what separates confident users from ones who silently accumulate ghost copies.

When "Deleted" Variables Persist: Diagnosing the Symptoms

If a variable still appears after you clear it, work through the likely causes in order of reversibility.

Symptom: clear x runs, but whos still shows x.

Cause 1: You misspelled the name, and MATLAB silently ignored the nonexistent name. Fix: check case and spelling against whos output. Cause 2: There are two variables differing only by case or by hidden whitespace in programmatically built names. Fix: use whos to see exact names, then clear the correct one. Cause 3: You cleared a local variable inside a function, not the base workspace copy. Fix: return to the base workspace and clear there, or pass data out intentionally rather than relying on side effects.

Symptom: A variable disappears but memory usage doesn't drop.

Cause: Another reference still points to the data—a handle object, a persistent variable, or an app data store. Fix: search for the name across functions, or use clear functionName to reset persistent state, and use clear classes if a class instance may be holding on.

Symptom: Editing a function's code has no effect.

Cause: MATLAB cached the old function. Fix: clear functionName or clear functions, then rerun. For a recompiled MEX file, clear mex.

Symptom: After editing a class file, objects behave according to the old definition.

Cause: Class cache. Fix: clear classes. Note that existing objects of the class can block redefinition; deleting the objects first or restarting MATLAB may be needed if clear classes warns about instances in use.

The stop condition: if clearing classes still fails and MATLAB warns that objects exist in the workspace, and you cannot identify them, restarting MATLAB is the reliable fallback. That's not a professional referral situation; it's the standard reset when cache state defies surgical clearing.

Saving Before You Clear, and Other Guardrails

Because clear and clearvars are irreversible within the session, a few habits prevent grief:

Save selectively with save('backup.mat', 'x', 'y') before clearing anything expensive to regenerate. Prefer clearvars -except over bare clear when you know which variables must survive. Avoid clear all inside reusable functions and scripts; it's a sledgehammer that reaches into function and MEX caches. Keep the command window and figures in mind: they're cleared by clc and close all, not by clear.

There's also a quiet correctness issue. Clearing a variable and then reintroducing a same-named one later in a long session can mask bugs—the fresh variable may lack properties the old one had, and code that worked before suddenly fails. Scripts that begin with clearvars and load data deliberately tend to be more reproducible than interactive sessions where state accumulates unpredictably.

Choosing Between Clear, Clearvars, and Clear All

The decision is really about scope and safety. For one or a few named variables, clear name is direct and portable. For bulk cleanup with exclusions or pattern matching, clearvars is the better tool, especially when you want its stronger memory behavior or its default refusal to touch globals. For resetting the whole in-memory state of a session—variables, functions, MEX files, classes—clear all does the job, but only when that's genuinely what you want.

A fair comparison across the same criteria (scope, globals handling, memory release, caching effects, script-safety) shows the mismatch: they aren't interchangeable commands; they're tools for different jobs that happen to share a verb. Treating clear as a synonym for clearvars, or either as a synonym for clear all, is where most errors begin.

The command prompt's case sensitivity, the difference between command syntax and function syntax, and the workspace-scope boundary are the three details that cause the majority of "it didn't delete" reports. Get those right, verify with whos, and variable management in MATLAB becomes a routine, predictable part of the workflow rather than a source of mystery.