extract first 4 letters from a string in matlab

60,824

Solution 1

A string is treated like a vector of chars. Try this:

>> string = '01 ED 01 F9 81 C6'; 
>> string(1:5), string(6:11), string(12:17)

ans =
01 ED

ans =
 01 F9

ans =
 81 C6

string in this example is a variable not a method. string(1) returns the first char in the array (or vector) called string.

Solution 2

If you want only the non-whitespace characters you could use the ISSPACE function to remove the whitespace and then character array indexing to access the characters:

>> s = '01 ED 01 F9 81 C6';
>> s = s(~isspace(s))

s =

01ED01F981C6

>> s(1:4)

ans =

01ED

>> s(5:8)

ans =

01F9

>> s(9:end)

ans =

81C6

You can expand this to process multiple lines of a character array using RESHAPE to transform the result of the space removal back to a 2D-array and then referencing the extra dimension:

 s = ['01 ED 01 F9 81 C6'; 'F8 CA DD 04 44 3B']

s =

01 ED 01 F9 81 C6
F8 CA DD 04 44 3B

>> s = reshape(s(~isspace(s)), size(s, 1), 12)

s =

01ED01F981C6
F8CADD04443B

>> s(:,1:4)

ans =

01ED
F8CA

>> s(:,5:8)

ans =

01F9
DD04

>> s(:,9:end)

ans =

81C6
443B
Share:
60,824

Related videos on Youtube

Dilip
Author by

Dilip

Updated on March 31, 2020

Comments

  • Dilip
    Dilip about 4 years

    How can I extract the first 4 or the middle 4 or last four letters of a string example: when the string reads 01 ED 01 F9 81 C6?

  • Dilip
    Dilip about 13 years
    @trolle3000 and b3: thanks but what if the file has a bunch of values 'C1 F3 81 F6 81 C5 ' '01 F0 41 F7 01 C6 ' '41 ED C1 F7 01 C6 ' then how do I work on it?
  • Dilip
    Dilip about 13 years
    thank you but my problem is I have a file with 4000 lines of hex code I want to split them in bulk how can I do this?
  • b3.
    b3. about 13 years
    @Dilip: See my edited answer above which describes how to process multiple lines.

Related