Copy text from a string that meets a certain condition MATLAB

119 Views Asked by At

i have a strings from a text file:

20130806_083642832,!AIVDM,1,1,,B,13aFeA0P00PEqQNNC4Um7Ow`2@O2,0*5E

20130806_083643032,!AIVDM,2,1,4,B,E>jN6<0W6@1WPab3bPa2@LtP0000:uoH?9Ur,0*50

i need to go through the characters and extract the date at the start then the message that starts after B, (but could also be A,) up until ,0

Any thoughts?

2

There are 2 best solutions below

0
On

Ok, there are much more elegant ways to solve this, but my following example will give you a feeling on how to manipulate strings in MatLab (Which might be the thing you are having problems with). Here you go:

String='20130806_083642832,!AIVDM,1,1,,B,13aFeA0P00PEqQNNC4Um7Ow`2@O2,0*5E'

for i=1:length(String)
   if(strcmp(String(i),'B'))     %or strcmp(String(i),'A')
       for j=i:length(String)    %or "for j=length(String):i" if you meant the last 0 ;) 
           if(strcmp(String(j),'0'))

               String2=String(i:j)

               break
           end
       end
       break
   end
end

Output

String =

20130806_083642832,!AIVDM,1,1,,B,13aFeA0P00PEqQNNC4Um7Ow`2@O2,0*5E


String2 =

B,13aFeA0

Just play around with string indexing and with strcmp or strcmpi and you'll get a feeling and will be able to write much nicer expressions.

Now try extracting the date by yourself!

Hope that helps!

0
On

Without loops you could do something like this:

startString = ['20130806_083642832,!AIVDM,1,1,,B,13aFeA0P00PEqQNNC4Um7Ow`2@O2,0*5E'];
startPosition = find(startString == 'B') + 1;
if ~startPosition
    startPosition = find(startString == 'A') + 1;
end
tmpMessage = startString(startPosition:end);

endPosition = find(tmpMessage == '0') - 1;
outMessage = tmpMessage(1:endPosition(1))

dateString = startString(1:8)

This gives the output:

outMessage = ,13aFeA
dateString = 20130806