MATLAB: How to index into a structure/cell variable which is not yet evaluated and hence is not in the workspace

MATLABsubsref

I would like to do the following syntax in 1 line:
lst = {dir('*.jpg')};
lst{1}.name
I tried:
{dir('*.jpg')}{1}.name
However, MATLAB shows me the error message:
{dir('*.jpg')}{1}.name
Error: Invalid expression. When calling a function or indexing a variable, use parentheses. Otherwise, check for mismatched
delimiters.
Is there a workaround to do the indexing in 1 line?

Best Answer

You can use the 'subsref' function to do the indexing work in 1 line:
subsref(subsref({dir('*.jpg')},struct('type','{}','subs',{{1}})),struct('type','.','subs','name'))
For better understanding, this long syntax can be deconstructed into 5 lines:
S1.type='{}';
S1.subs={1};
S2.type='.';
S2.subs='name';
subsref(subsref({dir('*.jpg')},S1),S2)
For more information about the 'subsref' function, please see the link: