How to convert a string to array or matrix?

조회 수: 2 (최근 30일)
Thuan Nguyen
Thuan Nguyen 2017년 11월 3일
댓글: Walter Roberson 2017년 11월 3일
Hi everyone, I want to convert a string '[2:0.5:4]' to an array. Thanks in advance.

채택된 답변

Walter Roberson
Walter Roberson 2017년 11월 3일
With those quotation marks, it is already an array -- a character vector.
Perhaps you want it expanded into the numeric matrix [2 2.5 3 3.5 4] ?
If so, the easiest way is to use str2num() on it. That will eval() the string. If you had total control over what went into the string, and if you are not doing code generation, then that can be enough.
If you are doing code generation or if you do not have total control of the string, then you can:
fmt1 = '[%f:%f:%f]';
fmt2 = '%f:%f:%f'
parts = sscanf(TheString, fmt1);
if isempty(parts)
parts = sscanf(TheString, fmt2);
end
if length(parts) < 2
error('Sorry, that is not a range I recognize')
end
if length(parts) == 2
range = parts(1) : parts(2);
else
range = parts(1) : parts(2) : parts(3);
end
  댓글 수: 3
Walter Roberson
Walter Roberson 2017년 11월 3일
str2func(['@(x,y)' a])
Walter Roberson
Walter Roberson 2017년 11월 3일
Again if you do not have total control over the string then this is dangerous. Suppose the user had entered delete('*.*')

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by