Group the array with similar strings
古いコメントを表示
How can I find the strings that have similar string in them:
A=['x_B1_0_s_0' , 'x_B1_0_s_1', 'x_B1_0_s_2', ' y_B1_2_s_0' , 'y_B1_2_s_1', ' y_B1_2_s_2' ,' x_B2_0_s_0' ,
'x_B2_0_s_1' ,' x_B2_0_s_2' , 'y_B2_2_s_0' , 'y_B2_2_s_1' , 'y_B2_2_s_2' ]
I need to group above array to have 4 groups of strings like this:
B=['x_B1_0', 'y_B1_2', 'x_B2_0', 'y_B2_2']
Any idea how to do so?
採用された回答
その他の回答 (1 件)
Max Murphy
2019 年 11 月 24 日
Seems like you are trying to parse out a bunch of variable names and associated values and group them in a table. Ideally, it would work something like this:
% I assume it should be a cell array of char, or an array of strings
A={'x_B1_0_s_0' , 'x_B1_0_s_1', 'x_B1_0_s_2', ... % formatted
'y_B1_2_s_0' , 'y_B1_2_s_1', 'y_B1_2_s_2' , ...
'x_B2_0_s_0' , 'x_B2_0_s_1' , 'x_B2_0_s_2' , ...
'y_B2_2_s_0' , 'y_B2_2_s_1' , 'y_B2_2_s_2' };
% varExp can be changed, but does the parsing using regexp basically
varExp = '(?<label>[xy]_B\d_\d)_(?<data>\w)';
S = dynamicVarParser(A,varExp);
T = struct2table(S);
And here is the helper function I wrote:
function S = dynamicVarParser(A,varExp)
%% DYNAMICVARPARSER Parse cell array of char vectors into struct fields
%
% S = dynamicVarParser(A,nLevels);
%
% e.g.
% S = dynamicVarParser({'x_B1_0_s_0','x_B2_0_s_2'});
%%
if nargin < 2
varExp = '(?<coord>[xy])_(?<group>\w+)_(?<time>\d+)_[s]_(?<radius>\d)';
end
S = regexp(A{1},varExp,'names');
for i = 2:numel(A)
S(i) = regexp(A{i},varExp,'names');
end
end
Note that if you call it without varExp it has a default expression that is different from the one I coded above; that reflects a possible different grouping that may be useful to you based on this question, not sure what your data looks like at the end of the day.
カテゴリ
ヘルプ センター および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!