Using a function handle to determine the length of a matrix represented by a string in a cell array

1 view (last 30 days)
I have a cell array that contains strings of several variable names. Each variable represents a row vector.
K>> A=[3 4 5 6]
A =
3 4 5 6
K>> vars=[{'A' };{'i' };{'ii'};{'j' }]
vars =
4×1 cell array
{'A' }
{'i' }
{'ii'}
{'j' }
I can easily determine the length of one of those vectors using this command:
K>> length(eval(cell2mat(vars(1))))
ans =
4
but when I try to use a function handle to do the same thing, I get an error:
K>> XX=@(x)length(eval(cell2mat(x)))
XX =
function_handle with value:
@(x)length(eval(cell2mat(x)))
K>> XX(vars(1))
Error using eval
Undefined function or variable 'A'.
Error in seq>@(x)length(eval(cell2mat(x)))
This doesn't work either:
K>> XX=@(x)length(eval(cell2mat(vars(x))))
XX =
function_handle with value:
@(x)length(eval(cell2mat(vars(x))))
K>> XX(1)
Error using eval
Undefined function or variable 'A'.
Error in seq>@(x)length(eval(cell2mat(vars(x))))
I'm ultimately trying to use cellfun() to return a vector that contains the length of each matrix represented by vars, but it's getting hung up on the function handle part. I can use a for loop to accomplish the same thing of course, but I'd prefer to accomplish this on one line and I'm really curious to know why it isn't working.

Accepted Answer

Walter Roberson
Walter Roberson on 15 Jan 2020
You would have to use evalin('caller') to continue your hack. But the best thing would be Don't Do That. Using dynamic top level variable names causes more problems than they are worth.
  3 Comments
Philip M
Philip M on 16 Jan 2020
Yep yep. I just recently discoverd the eval command and it's potential. I kept seeing warnings not to use it but I like to learn things the hard way. Between posting my question this morning and now, I saw that eval("i=1:4") was updating the variable in the workspace but not within the actual code.... Noped my way right on out of there and now I'm using cell arrays.

Sign in to comment.

More Answers (0)

Products


Release

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!