str2num strange behaviour
조회 수: 1 (최근 30일)
이전 댓글 표시
Dear, I have this code:
svmKernel ={'rbf','gaussian', 'linear','2','3','4'};
for k=1:numel(svmKernel)
[p, status] = str2num(svmKernel{k});
if ~status; t = templateSVM('Standardize',true,'KernelFunction',svmKernel{indK});
else; t = templateSVM('Standardize',true,'KernelFunction','polynomial', 'PolynomialOrder', p); end
WHY str2num returns p =
Linear Function:
Parameters: [1×1 struct]
and status = 1 when issuing [p,status] = str2num('linear')?
[p, status] = str2num('linear')
Linear Function:
Parameters: [1×1 struct]
status =
logical
1
댓글 수: 6
채택된 답변
Stephen23
2019년 8월 23일
편집: Stephen23
2019년 8월 23일
"str2num strange behaviour"
It is not strange behavior at all: str2num (unfortunately) relies on eval, as the str2num help clearly states "...str2num uses the eval function, which can cause unintended side effects when the input includes a function name." You provided str2num a function name to evaluate... you can easily find out which function it is evaluating:
which linear -all
As the str2num documentation recommends, you could avoid the whole problem simply by using str2double (which could be called before the loop), then using isnan.
댓글 수: 3
Steven Lord
2019년 8월 23일
Another solution would be to avoid trying to convert that text data into numbers entirely.
svmKernel = {{'rbf'}, ...
{'gaussian'}, ...
{'linear'}, ...
{'polynomial', 'PolynomialOrder', 2}, ...
{'polynomial', 'PolynomialOrder', 3}, ...
{'polynomial', 'PolynomialOrder', 4}};
for k=1:numel(svmKernel)
t = templateSVM('Standardize',true,'KernelFunction', svmKernel{k}{:});
end
The command svmKernel{k} extracts the contents of each cell inside svmKernel in turn. Since I have cell arrays inside each of those cells, I can turn them into a comma-separated list. This is the technique shown in the "Function Call Arguments" example in the "How to Use the Comma-Separated Lists" item on that documentation page.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Cell Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!