필터 지우기
필터 지우기

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