Using cellfun with function that can return nothing
조회 수: 7 (최근 30일)
이전 댓글 표시
I am trying to use the cellfun function to execute the evalin function on a cell array of char vectors, which correspond to elements in the base workspace. Sometimes the char vectors are empty, in order to ensure the order of the elements matches with other cell arrays of data.
a = Simulink.Signal;
b = Simulink.Signal;
C = {'a', '', 'b'};
X_values = cellfun(@(x) evalin('base', x), C, 'UniformOutput', false);
Executing the last line gives the error:
Error using @(x) evalin('base', x)
Error: This statement is incomplete.
Is seems that the issue is that evalin returns nothing when it does not find the '' in the base workspace. Is there some way to make the cellfun work in this case, or do I need to use a loop?
댓글 수: 0
채택된 답변
Guillaume
2019년 9월 4일
편집: Guillaume
2019년 9월 4일
I'm not going to comment on the wisdom of using evalin.
The problem is not with cellfun. You'll get the same error if you do:
val = evalin('base', '');
The error message could be better as it looks like you're seeing an implementation detail of evalin, but clearly, '' is not allowed as an input for evalin.
The workaround would be to create your own wrapper that catches errors with evalin (would also help if the variable name you pass is not actually a variable):
function value = evalin_with_catch(varname) %no point in asking for the workspace. It can only be base here
try
value = evalin('base', varname)
catch
value = 'INVALID VARIABLE'; %whatever value you want returned.
end
end
then:
X_values = cellfun(@evalin_with_catch, C, 'UniformOutput', false);
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!