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.
0 个评论
采纳的回答
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!