Nested Indexing in a Single Line command
Ältere Kommentare anzeigen
Is it possible to extract different data in the following structured string using a single line command?
exp={'George: A5 == BB';...
'Anna: C3 == DD';...
'Smith: E2 == FFF';...
'Ken: G8 == HHHH'};
For example, the obvious method to extract HHHH is the following:
mystr1=split(exp(end),': ',2);
mystr2=split(mystr1(:,2),' == ',2);
mystr2(end)
Can you suggest a single line of command to extract HHHH? Please note all names, right-hand and left-hand sides of the equations can be anything with different lenghts or characters. Only : and == characters are unchanged. The code needs be be universal meaning it sould extract anything (index 3 and 1 for Smith or index 2 and 2 for C3 or index end and end for HHHH) only using a single line command.
4 Kommentare
Bob Thompson
am 14 Jan. 2019
Why do you need to split at ':' and '=='? Splitting at just the equals should work fine.
Also, you can probably use regexp to split at both special characters.
mystr = regexp(exp{end},'\W','split');
mystr{end};
I have not tested this for specific syntax, but the concept should be sound.
Bob Thompson
am 14 Jan. 2019
So, all you're looking to do is display the answer? This can be done by unsurpressing the regexp command (remove the semicolon at the end of the line).
S H
am 14 Jan. 2019
Akzeptierte Antwort
Weitere Antworten (1)
>> C = {'George: A5 == BB'; 'Anna: C3 == DD'; 'Smith: E2 == FFF'; 'Ken: G8 == HHHH'};
>> D = regexp(C,'^(\w+):\s*(\w+)\s*==\s*(\w+)','tokens','once');
>> horzcat(D{:}) % or VERTCAT, depending on your needs.
ans =
[1,1] = George
[2,1] = A5
[3,1] = BB
[1,2] = Anna
[2,2] = C3
[3,2] = DD
[1,3] = Smith
[2,3] = E2
[3,3] = FFF
[1,4] = Ken
[2,4] = G8
[3,4] = HHHH
4 Kommentare
Walter Roberson
am 14 Jan. 2019
LastCell = @(C) C{end};
then
LastCell( regexp(C,'^(\w+):\s*(\w+)\s*==\s*(\w+)','tokens','once') )
S H
am 14 Jan. 2019
Walter Roberson
am 14 Jan. 2019
C = {'George: A5 == BB'; 'Anna: C3 == DD'; 'Smith: E2 == FFF'; 'Ken: G8 == HHHH'};
disp(char(regexprep(C, '^.*==\s*', '')))
Kategorien
Mehr zu Matrices and Arrays finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!