extract first 4 letters from a string in matlab
How can 开发者_如何学CI 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?
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
.
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
As trolle3000 and b3 mentioned, you use brackets containing indices to extract subsets of the string.
To answer the additional question of how you work on the string, I suggest that you split the string at each space, and convert from hexadecimal to decimal numbers.
s = '01 ED 01 F9 81 C6';
hex2dec(regexp(s, ' ', 'split'))
ans =
1
237
1
249
129
198
精彩评论