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

1 次查看(过去 30 天)
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.

采纳的回答

Walter Roberson
Walter Roberson 2020-1-15
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 个评论
Philip M
Philip M 2020-1-16
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by