How to get the order indices in a character array?

조회 수: 20 (최근 30일)
Akbar
Akbar 2018년 7월 6일
댓글: Akbar 2018년 7월 7일
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.
  댓글 수: 1
Ben Frankel
Ben Frankel 2018년 7월 6일
Do you know that the 'x_air', ... will be unique and won't contain any ','s?

댓글을 달려면 로그인하십시오.

채택된 답변

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