用字符串绘制一个矩形

时间:2018-01-19 06:22:54

标签: string matlab drawing

我有一个如下字符串:

  

A = AREA(-364320 -364320)(365640 365640);

现在我想在MATLAB中绘制一个带有A sting位置的矩形。 我用这段代码画一个矩形:

rectangle('Position',[-364320 -364320 364320 364320],'FaceColor',[0 .9 .8])

但我想用A字符串绘制它。请帮我解决这个问题。

2 个答案:

答案 0 :(得分:2)

直接您无法使用,但您可以使用strsplitstr2num拆分字符串并将其转换为数字。 但是,正如Wolfie answer指出的那样,最好使用str2double

代码获取:

A =' AREA ( -364320 -364320 ) ( 365640 365640 ) ';
b=strsplit(A)
b =
  1×11 cell array
  Columns 1 through 8
    ''    'AREA'    '('    '-364320'    '-364320'    ')'    '('    '365640'
  Columns 9 through 11
    '365640'    ')'    ''
a_array=str2double(b([4 5 8 9]));
rectangle('Position',a_array,'FaceColor',[0 .9 .8])

请注意,如果您的字符串略有不同,可能需要查看b变量中是否有空格。

使用str2num的原始代码:

A =' AREA ( -364320 -364320 ) ( 365640 365640 ) ';
b=strsplit(A,{'(',')'})
b =
  1×5 cell array
    ' AREA '    ' -364320 -364320 '    ' '    ' 365640 365640 '    ' '
a_array=str2num([b{2} b{4}]);
rectangle('Position',a_array,'FaceColor',[0 .9 .8])

答案 1 :(得分:2)

您可以regexp使用'match'选项直接提取数字

% Extract strings which match:
%    -?  means 0 or 1 - signs
%    \d+ means 1 or more digits
% Using the 'match' argument returns the matching strings, rather than their indices
% Use str2double to convert from array of strings to numerical array
B = str2double(regexp(A, '-?\d+', 'match'));
% Create the rectangle
rectangle('Position', B, 'FaceColor', [0 .9 .8])

最好使用str2double代替str2num,因为它不会使用eval

无论字符串的格式如何,此方法都会选择数值。