extract 2 data(temperature) from string
Show older comments
Code is
Str = [' <data seq="0" <temp8.0</temp <data seq="1" <temp6.9</temp '];
Str(strfind(Str, '>')) = [];
Key_1 = '<temp';
Index_1 = strfind(Str, Key_1);
Value_1 = sscanf(Str(Index_1 + length(Key_1):end),'%f');
But this code express in workspace
Value_1 = 8
I want to express in workspace
Value_1 = 8
Value_2 = 6.9
How can I make code ?
Accepted Answer
More Answers (1)
This would be a good place for regular expressions, but I'm a dweeb when it comes to trying to write the proper parsing expression...with string operations, I'd do this something like--
>> Str = [' <data seq="0" <temp8.0</temp <data seq="1" <temp6.9</temp '];
>> t=tokens(Str,'<');
>> Values=str2num(t(t(:,1)=='t',5:end))
Values =
8.0000
6.9000
>>
The above takes advantage that the string 'temp' trailing the value is returned with the leading '/' so the first character in the resulting array of tokens being 't' identifies the desired rows. Then, since it's a fixed-length string of four leading characters, simply return the remainder of the string '5:end' and convert to numeric.
tokens is my little utility routine--
>> type tokens
function tok = tokens(s,d)
% Simple string parser returns tokens in input string s
%
% T=TOKENS(S) returns the tokens in the string S delimited
% by "white space". Any leading white space characters are ignored.
%
% TOKENS(S,D) returns tokens delimited by one of the
% characters in D. Any leading delimiter characters are ignored.
% Get initial token and set up for rest
if nargin==1
[tok,r] = strtok(s);
while ~isempty(r)
[t,r] = strtok(r);
tok = strvcat(tok,t);
end
else
[tok,r] = strtok(s,d);
while ~isempty(r)
[t,r] = strtok(r,d);
tok = strvcat(tok,t);
end
end
>>
NB: It's a very bad idea to "poof" variables into the workspace with names such as you've written; it leads to requiring eval to process them later and that just leads to a location where "there be dragons" and is to be avoided. Use an array as shown instead.
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!