In MATLAB, use ~= to test inequality; it returns true where two values differ.
You’re writing a script, you compare two values, and MATLAB throws you a result that feels off. Most of the time, it’s not MATLAB being odd. It’s the type of data you’re comparing, the shape of the arrays, or the kind of “equality” you really meant.
This article clears up what “does not equal” means in MATLAB across numbers, arrays, strings, tables, and objects. You’ll also get patterns that stay readable when your code grows.
Does Not Equal In MATLAB For Everyday Comparisons
The not-equal operator in MATLAB is ~=. Use it when you want an element-by-element comparison. That detail matters: for arrays, MATLAB checks each position and returns a logical array of the same size.
Start with the simple rule:
A ~= BcomparesAandBelement-by-element.- The result is logical:
truewhere elements differ,falsewhere they match. - Array sizes usually need to align, or you need a size rule (scalar expansion) that makes sense for your case.
If you’re coming from languages that use !=, that’s the main translation. MATLAB uses ~ as logical NOT, so inequality becomes ~=.
What ~= Returns And Why That Return Shape Matters
When you compare scalars, the result is one logical value. When you compare arrays, you get an array of logical values. That’s a feature, not a trap, as long as you treat the output the right way.
Scalar Against Scalar
If both inputs are single values, you’ll get one logical back:
3 ~= 4returnstrue3 ~= 3returnsfalse
Array Against Array
If both inputs are arrays of the same size, MATLAB checks each position. The result has the same size as the inputs. That’s perfect for masking, filtering, and conditional indexing.
Where people get stuck is expecting one true/false for the whole array. If you want a single decision, you choose a rule:
- “Any element differs” → wrap with
any(...) - “All elements differ” → wrap with
all(...) - “Arrays match exactly” → consider
isequal(with caveats forNaN)
Scalar Expansion
MATLAB can compare an array to a scalar by expanding the scalar across the array. That’s handy when you’re checking against a threshold, a sentinel value, or a flag.
Still, be deliberate. Scalar expansion reads clean when the scalar is a constant or a named variable that tells the story.
Numeric Comparisons That Stay Stable
For integers and exact values, ~= works the way you expect. With floating-point numbers, direct inequality can mislead you. That’s not a MATLAB quirk; it’s how floating-point representation works.
Integers And Exact Values
When your numbers are integers, or values you know are exact in binary form, ~= is a solid choice. You can use it in conditions, logical indexing, and vectorized checks without drama.
Floating-Point Values Need A Tolerance
If your values come from math operations, file imports, sensors, or iterative solvers, treat “not equal” as “not close enough.” That means comparing the difference to a tolerance.
Common patterns:
- Absolute tolerance: check whether
abs(A - B) > tol - Relative tolerance: check whether
abs(A - B) > tol * max(1, abs(B)) - Mixed tolerance: combine absolute and relative limits when values span ranges
Pick tol based on your data scale and what “same” means in your domain. A small tolerance that matches your measurement noise beats a random constant pulled out of thin air.
NaN And Missing Values
NaN is special. A comparison like NaN ~= NaN returns true because NaN is not equal to anything, including itself. That can be useful when you want to detect unknown values, but it can also trip you if you meant “treat missing as equal.”
When you want “same, counting NaN as same,” use a deliberate approach, such as using isnan checks plus a tolerance rule for the non-NaN parts, or use functions that support the semantics you want.
Text And String Inequality Without Headaches
Text comparisons in MATLAB depend on whether you’re using string arrays (double quotes) or character vectors (single quotes). The good news: MATLAB gives you clear tools, you just need to choose the right one.
String Arrays Versus Character Vectors
A string scalar looks like "hello". A character vector looks like 'hello'. They can represent similar content but behave differently in some operations.
For comparisons that read clean and behave consistently across text inputs, use functions designed for text equality:
strcmpfor case-sensitive equality testsstrcmpifor case-insensitive equality tests
If you need “does not equal” logic, you can negate the result of these functions with ~:
~strcmp(a, b)means the texts differ~strcmpi(a, b)means the texts differ ignoring case
Why Not Use ~= Directly For Text
Direct relational operators on text can behave in ways that don’t match what you mean, especially with different shapes, different encodings, or cell arrays. Text functions express intent. That makes later debugging a lot nicer.
Quick Pick Table For Not-Equal Logic
You can use the table below as a practical chooser. It maps the “what I’m comparing” situation to the cleanest approach, plus a note on what to watch.
| What You’re Comparing | Best Not-Equal Check | Notes That Save Time |
|---|---|---|
| Two scalar integers | A ~= B |
Returns one logical value. |
| Two same-size numeric arrays | A ~= B |
Returns a logical array; wrap with any or all if you want one decision. |
| Array versus scalar threshold | A ~= c or A > c |
Scalar expands across the array; keep names clear. |
| Two floating-point values | abs(A - B) > tol |
Pick tol based on scale and noise. |
| Floating-point arrays | abs(A - B) > tol |
Use logical indexing to isolate mismatches. |
| Text (char vectors) | ~strcmp(a, b) |
Reads as intent; avoids shape surprises. |
| Text (case-insensitive) | ~strcmpi(a, b) |
Handy for user input and file labels. |
| Whole-array exact match rule | ~isequal(A, B) |
isequal treats NaN as not equal; handle missing values on purpose. |
Use Not-Equal Results In Real Code
Once you accept that array comparisons return arrays, MATLAB opens up. You can isolate the mismatches, count them, or act only where values differ.
Logical Indexing To Pull Mismatches
A logical mask from ~= is often the cleanest “debug print” you can make. You can use it to find the exact positions that differ and inspect them in one shot.
- Make a mask:
m = A ~= B - Find indices:
idx = find(m) - Pull values:
A(m)andB(m)
This pattern scales. It works for vectors, matrices, and higher-dimensional arrays.
Turn An Elementwise Result Into One Decision
Sometimes you need a single true/false for a condition in an if statement. Decide what “not equal” means at the whole-array level, then use the matching reducer:
any(A ~= B, "all")answers: does at least one element differ?all(A ~= B, "all")answers: do all elements differ?
The "all" flag makes the intent explicit: reduce across every element, not just along one dimension.
Operator Details From MathWorks
If you ever want to confirm the exact operator meanings and how MATLAB lists them, MathWorks keeps a concise reference for relational operators, including the not-equal symbol. Here’s the official operator table: MATLAB Operators and Special Characters.
For the ~= behavior itself, including edge cases like NaN handling and class overloading through ne, the function reference is also useful: “ne” (Determine inequality).
Data Types That Change What “Not Equal” Means
MATLAB supports many array types beyond plain doubles. Most of the time, ~= still works, yet the meaning can shift based on the type’s rules.
Complex Numbers
For complex values, MATLAB compares both the real and imaginary parts. If either part differs, the result is true for that element. That’s what most engineers expect, but it’s worth stating when you’re tracking phase or frequency-domain outputs.
Categorical Arrays
With categoricals, inequality compares category membership. Missing categorical values can behave differently than missing numeric values, so treat missing categories as a separate state and handle them on purpose if your logic depends on it.
Tables And Timetables
Tables can support elementwise comparisons, but the behavior depends on what’s inside each variable. A table column holding strings has different comparison rules than one holding doubles. When you want “row differs,” it’s often cleaner to compare one variable at a time and combine results.
Handle Objects
With handle objects, “equality” can mean “same handle” rather than “same property values.” If you’re comparing objects, be clear about what you want: identity or content. MATLAB supports both concepts, and mixing them can create confusing bugs.
Second Table: Patterns That Keep Comparisons Readable
This table focuses on how to write comparisons that stay readable six weeks later. It’s less about syntax and more about keeping intent obvious.
| Scenario | Readable Pattern | Why It Helps |
|---|---|---|
| Check if any element differs | any(A ~= B, "all") |
One decision with clear meaning. |
| Find mismatch positions | m = A ~= B; idx = find(m) |
Makes debugging direct. |
| Float comparison | abs(A - B) > tol |
Matches numeric reality. |
| Float arrays with mixed scale | abs(A - B) > (atol + rtol*abs(B)) |
Stable across large and small values. |
| Text mismatch (case-sensitive) | ~strcmp(a, b) |
Intent reads like plain English. |
| Text mismatch (case-insensitive) | ~strcmpi(a, b) |
Good for user inputs and filenames. |
| Count how many differ | nnz(A ~= B) |
Gives a clean mismatch count. |
Common “Not Equal” Mistakes And Quick Fixes
Most bugs around inequality come from silent assumptions. Here are the ones that show up again and again, plus the fix that keeps code clean.
Using = Instead Of == Or ~=
= assigns. == compares equality. ~= compares inequality. If you see an error inside an if statement, check that you didn’t slip an assignment where a comparison belongs.
Expecting One True/False From An Array Comparison
If you write if A ~= B and A is an array, MATLAB won’t accept it, since if needs one logical. Decide the rule you want, then use any or all with "all".
Forgetting About NaN Behavior
If your data can contain NaN, inequality checks can light up positions that look “same” in your mental model. Treat missing values as their own case. Handle them first, then compare what’s left.
Comparing Text With Numeric Operators
Text comparisons belong to text functions. If your variables hold file names, IDs, labels, or user inputs, use strcmp and its relatives. Your intent stays clear, and you sidestep weird shape or type surprises.
Practical Workflow When A Comparison Looks Wrong
When an inequality check produces a result you didn’t expect, a short workflow usually locates the issue in minutes.
Step 1: Confirm The Types
Check class(A) and class(B). Also check whether they are string arrays, character vectors, cell arrays, or tables. Type differences explain a lot of “wait, why” moments.
Step 2: Confirm The Sizes
Run size(A) and size(B). If they don’t line up, MATLAB may error or it may apply scalar expansion. Either way, make the size relationship explicit in code, so future edits don’t change the meaning by accident.
Step 3: Inspect The Mismatch Mask
Compute m = A ~= B, then check nnz(m) to see how many positions differ. Pull the mismatched elements with A(m) and B(m). That’s often all you need to spot a rounding issue, an unexpected missing value, or a data import artifact.
Step 4: Switch To A Tolerance If Needed
If you see mismatches that are tiny numeric differences, move to a tolerance check. Name the tolerance variable with intent, like sensorTol or solverTol, so readers know why it exists.
When To Prefer A Function Over ~=
~= is great for elementwise logic. Still, there are cases where a function reads better and matches the semantics you need.
Use ne When You Need Operator Overloading
Most of the time you’ll write A ~= B. Under the hood, MATLAB can route that comparison through ne(A,B). That matters when you’re working with custom classes that define what inequality should mean.
Use isequal When You Want Whole-Value Matching
If you need a single true/false for “these arrays match exactly in size and content,” isequal is direct. Keep its behavior with NaN in mind. If you want special rules for missing values, build them into your comparison rather than hoping a general-purpose function guesses your intent.
Wrap-Up: Write The Inequality You Actually Mean
MATLAB gives you a clean not-equal operator, plus a set of functions for cases where equality is more than a symbol. Use ~= for elementwise checks, then decide whether you need any, all, or a tolerance for a whole-array decision.
If your comparisons still feel “wrong,” it’s almost always type, size, missing values, or floating-point scale. Once you check those four, the fix usually becomes obvious.
References & Sources
- MathWorks.“MATLAB Operators and Special Characters.”Lists MATLAB relational operators, including ~= for not equal.
- MathWorks.“ne – Determine inequality – MATLAB.”Documents A ~= B behavior, return types, and related details such as NaN handling and overloading.
