poster
2019-12-14, 20:46
是否可以对下面的循环进行矢量化处理?
% 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 (http://www.mathworks.com/help/techdoc/ref/cell2struct.html)
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'
更多&回答... (https://stackoverflow.com/questions/5413080)
% 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 (http://www.mathworks.com/help/techdoc/ref/cell2struct.html)
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'
更多&回答... (https://stackoverflow.com/questions/5413080)