Reputation: 1
[23567,0,0,0,0,0]
and other value is [452221,0,0,0,0,0]
and the value should be contineously displaying about 100 values and then i want to display only the sensor value like in first sample 23567
and in second sample 452221
, only the these values have to display . For that I have written a code
value = str2double(str(2:7));
see here my attempt
so I want to find the comma in the output and only display the value before first comma
Upvotes: 0
Views: 303
Reputation: 14316
As proposed in a comment by excaza, MATLAB has dedicated functions, such as sscanf
for such purposes.
sscanf(str,'[%d')
which matches but ignores the first [
, and returns the next (i.e. the first) number as a double variable, and not as a string.
Still, I like the idea of using regular expressions to match the numbers. Instead of matching all zeros and commas, and replacing them by ''
as proposed by Sardar_Usama, I would suggest directly matching the numbers using regexp
.
You can return all numbers in str
(still as string!) with
nums = regexp(str,'\d*','match')
and convert the first number to a double variable with
str2double(nums{1})
To match only the first number in str
, we can use the regexp
nums = regexp(str,'[(\d*),','tokens')
which finds a [
, then takes an arbitrary number of decimals (0-9), and stops when it finds a ,
. By enclosing the \d*
in brackets, only the parts in brackets are returned, i.e. only the numbers without [
and ,
.
Final Note: if you continue working with strings, you could/should consider the regexp
solution. If you convert it to a double anyways, using sscanf
is probably faster and easier.
Upvotes: 1
Reputation: 19689
You can use regexprep
as follows:
str='[23567,0,0,0,0,0]' ;
required=regexprep(str(2:end-1),',0','')
%Taking str(2:end-1) to exclude brackets, and then removing all ,0
If there can be values other than 0
after ,
, you can use the following more general approach instead:
required=regexprep(str(2:end-1),',[-+]?\d*\.?\d*','')
Upvotes: 0