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에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!