用字符串绘制一个矩形



我有一个如下所示的字符串:

A = 面积 ( -364320 -364320 ( ( 365640

365640 ( ;

现在我想在 MATLAB 中绘制一个带有刺位置的矩形。我使用此代码绘制一个矩形:

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

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

您不能直接使用,但是您可以使用strsplitstr2num来拆分字符串并将其转换为数字。但是,正如沃尔夫回答所指出的那样,最好使用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])

您可以将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

此方法只是挑选出数值,而不考虑字符串的格式。

相关内容

最新更新