Matlab中一行访问数组元素:能否将两行代码合并为f(x)[i]形式?
Hey there! I totally get the frustration here—coming from other languages where f(x)[i] works seamlessly, it's super annoying when MATLAB throws an error for this syntax. Let's break down how to handle this, including ways to combine those two lines of code into a single line, depending on your MATLAB version.
1. The "Classic" (and Most Readable) Approach: Temporary Variables
First, let's start with the standard MATLAB way that works in every version. If your original code looks like this:
result = f(x); element = result(i);
While this is two lines, it's the most readable option and avoids any version-specific quirks. That said, if you really want to condense it into one line, keep reading.
2. For Older MATLAB Versions (Pre-R2021b): Use subsref
MATLAB's underlying indexing system uses the subsref function under the hood, so you can call it directly to replicate the behavior you want in one line:
element = subsref(f(x), struct('type', '()', 'subs', {{i}}));
Let me break this down simply:
- The first argument is the array returned by
f(x) - The second argument is a struct defining the indexing rule:
'type', '()'tells MATLAB we're using standard array parentheses indexing'subs', {{i}}wraps your indexiin a cell array (a requirement for the function's syntax)
3. For MATLAB R2021b and Newer: Direct Indexing Works!
Great news if you're on a recent MATLAB version—MathWorks added support for direct indexing on function return values starting in R2021b. That means you can write exactly what you're used to from other languages (just swap brackets for parentheses, since MATLAB uses () for array indexing):
element = f(x)(i);
No extra functions or workarounds needed—this just works out of the box, just like f(x)[i] does in other languages.
4. A Flexible Alternative: Anonymous Function Wrapper
If you want a more readable workaround that works across all MATLAB versions, you can create a simple anonymous function to handle indexing:
get_idx = @(arr, idx) arr(idx); element = get_idx(f(x), i);
This keeps the code clean, and you can reuse the get_idx function for other arrays and indices throughout your script.
Quick Recap
- Pre-R2021b: Use
subsrefor an anonymous function to combine the lines into one - R2021b+: Just use
f(x)(i)directly—it's now fully supported! - Pro Tip: Don't feel forced to condense into one line if the two-line temporary variable approach is more readable. Clarity beats brevity most of the time.
内容的提问来源于stack exchange,提问作者Aleksejs Fomins

