MATLAB: Advise on accessing cell array containing structures

evalnested cell arrays

I have a cell array "wrkspcs" containing names of cell arrays as shown below (some entries omitted for brevity)
wrkspcs =
13×1 cell array
{'ZLH_151210_WrkSpc'}
{'MXG_151210_WrkSpc'}
{'LF_151223_WrkSpc' }
each entry refers to a 6×6 cell array in the workspace. Using eval, I can see the referenced cell array
>> eval(wrkspcs{1})
ZLH_151210_WrkSpc =
6×6 cell array
{1×1 struct} {[1]} {'16557'} {'1210'} {'zlh_1a'} {'ZLH_151210'}
{1×1 struct} {[2]} {'16557'} {'1213'} {'zlh_2a'} {'ZLH_151210'}
{1×1 struct} {[3]} {'16557'} {'1216'} {'zlh_3a'} {'ZLH_151210'}
{1×1 struct} {[1]} {'16676'} {'1210'} {'zlh_1b'} {'ZLH_151210'}
{1×1 struct} {[2]} {'16676'} {'1213'} {'zlh_2b'} {'ZLH_151210'}
{1×1 struct} {[3]} {'16676'} {'1216'} {'zlh_3b'} {'ZLH_151210'}
If I want to get the number of entries in the first workspace "ZLH_151210_WrkSpc", I can do
>> tmp=eval(wrkspcs{1});n = length(tmp(:,1))
n =
6
but if I try to eliminate the creation of the temporary variable "tmp" and access the length directly, I get the following error:
>> n = length(eval(wrkspcs{1})(:,1))
Error: ()-indexing must appear last in an index expression.
However, if I try the following everything is fine.
>> eval(['n = length(',wrkspcs{iloop},'(:,1))'])
n =
6
So, I am trying to understand which syntax rule I am violating in the second case and what is the "proper" way of obtaining the length without either creating the variable "tmp" or including the assignment in the 'eval' statement (which the Matlab documentation states I should try to avoid).
Any comments, insights, or suggested alternatives would be appreciated.

Best Answer

Unlike C++ or python, in MATLAB you can't directly index the output of a function. You firstly need to store the data in a separate variable and then index the variable that variable to access the required data. So what is happening here:
1) If first case: eval() is a MATLAB function and you are trying to further index its output. Which as already stated is not supported in MATLAB.
2) In the second case: you are effectively running the following command
n = length(ZLH_151210_WrkSpc(:,1))
i.e. indexing into a cell array. This a perfectly supported MATLAB syntax. Even in the first case, the following line will work
n = length(eval([wrkspcs{1}, '(:,1)']))
as you can see that again I am trying to index in the cell array, not the output of a function.
Note: Accessing variables using eval is a very bad idea. It makes your code slow and difficult to debug. For better coding practice, you should look into storing all the variables in a struct and then access the required data using field names.