How to get the order indices in a character array?

19 次查看(过去 30 天)
Here is my cell Array, consider it as an input:
ans =
7×1 cell array
{'x_air' }
{'v_air' }
{'p_headspace' }
{'p_environment' }
{'x_air_standard' }
{'N_StirrerSpeed [s^-1]'}
{'v_air;Sparger' }
And I have this character Array (consider as output):
ans =
'v_air,p_headspace,p_environment,x_air,x_air_standard,N_StirrerSpeed [s^-1],v_air;Sparger'
Wanted result:
indices = [2;3;4;1;5;6;7];
The idea is to know which Output is connected to which Input. How to do that?
Once the indices have been recorded, the Input Array will be renamed, but Connection are not changed. For ex.: if i rename 'x_air' at Input then i want to know that it goes to 4th Output.

采纳的回答

Kelly Kearney
Kelly Kearney 2018-7-6
c = {...
'x_air'
'v_air'
'p_headspace'
'p_environment'
'x_air_standard'
'N_StirrerSpeed [s^-1]'
'v_air;Sparger'};
str = 'v_air,p_headspace,p_environment,x_air,x_air_standard,N_StirrerSpeed [s^-1],v_air;Sparger';
[~,loc] = ismember(regexp(str,',','split'), c);
Results:
loc =
2 3 4 1 5 6 7
As Ben indicates in his comment above, this will only work if none of your target strings include commas. If they do, a little extra parsing will be needed.

更多回答(2 个)

Geoff Hayes
Geoff Hayes 2018-7-6
Akbar - if it is safe to assume that all elements in your string are separated by commas, you could use cellfun to consider each string and find its index in the original array. For example,
myData = {
'x_air'
'v_air'
'p_headspace'
'p_environment'
'x_air_standard'
'N_StirrerSpeed [s^-1]'
'v_air;Sparger'};
myStr = 'v_air,p_headspace,p_environment,x_air,x_air_standard,N_StirrerSpeed [s^-1],v_air;Sparger';
myStrSplit = strsplit(myStr,',')';
myStrIndices = cell2mat(cellfun(@(k)find(strcmp(myData,k) == 1), myStrSplit, 'UniformOutput',false));
We split the string, myStr, on the comma which will create a cell array of strings. We then iterate over each of these strings and look for it in the myData cell array. Since strcmp returns a one/true for a match, then we use find to return the index of that match. The myStrIndices will then be the desired indices of your output to input.

Ben Frankel
Ben Frankel 2018-7-6
编辑:Ben Frankel 2018-7-6
You can do this in two steps. First, replace the strings with their indices in the output string:
s = [the_output, ','];
for ii = 1:numel(the_input)
s = replace(s, [the_input{ii}, ','], [int2str(ii), ',']);
end
Next you can interpret the character array `s = '2,3,4,1,5,6,7,'` as num and take the transpose if you want a column vector:
indices = str2num(s).';

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by