Labfans是一个针对大学生、工程师和科研工作者的技术社区。 论坛首页 | 联系我们(Contact Us)
MATLAB爱好者论坛-LabFans.com
返回   MATLAB爱好者论坛-LabFans.com > 其它 > 资料存档
资料存档 资料存档
回复
 
主题工具 显示模式
旧 2019-12-14, 20:46   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,008
声望力: 66
poster 正向着好的方向发展
帖子 从MATLAB中的正则表达式匹配向量化变量创建

是否可以对下面的循环进行矢量化处理?

% String to parse (we want to create variables that are defined implicitly in the string): parseStr = 'cubeId=001000_X=10_Y=10_Z=10_minX=8590_maxX=9200_minY=8590_maxY=9200_minZ=87_maxZ=95'; % Splitting string for regexp matchStr = '=|_'; [start_idx, end_idx, extents, matches, tokens, names, splits] = ... regexp(parseStr, matchStr); % Inspecting the splits >> splits splits = Columns 1 through 8 'cubeId' '001000' 'X' '10' 'Y' '10' 'Z' '10' Columns 9 through 15 'minX' '8590' 'maxX' '9200' 'minY' '8590' 'maxY' Columns 16 through 20 '9200' 'minZ' '87' 'maxZ' '95' % Loop that we are interested in vectorizing: for ix = 1:2:numel(splits) fields.(splits{ix}) = splits{ix+1}; end % Result: >>fields fields = cubeId: '000900' X: '10' Y: '9' Z: '10' minX: '8590' maxX: '9200' minY: '7590' maxY: '8610' minZ: '87' maxZ: '95'

回答:

您可以使用CELL2STRUCT

cell2struct(splits(2:2:end),splits(1:2:end),2) ans = cubeId: '001000' X: '10' Y: '10' Z: '10' minX: '8590' maxX: '9200' minY: '8590' maxY: '9200' minZ: '87' maxZ: '95' 如果要让字段包含数字,可以改写为

cell2struct(cellfun(@str2double,splits(2:2:end),'uniformOutput',false),splits(1:2:end),2) 此外,您可以修改正则表达式,以便它立即返回一个结构(抱歉,我没有输入整个表达式):

regexp(parseStr,'cubeId=(?\d+)_X=(?\d+)','names') ans = cubeId: '001000' X: '10'

更多&回答...
poster 当前离线   回复时引用此帖
回复

主题工具
显示模式

发帖规则
不可以发表新主题
不可以发表回复
不可以上传附件
不可以编辑自己的帖子

启用 BB 代码
论坛禁用 表情符号
论坛启用 [IMG] 代码
论坛启用 HTML 代码



所有时间均为北京时间。现在的时间是 04:41


Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.