필터 지우기
필터 지우기

Extracting numbers from array of cells

조회 수: 33 (최근 30일)
Dan H
Dan H 2019년 7월 9일
댓글: madhan ravi 2019년 7월 10일
Hello,
when reading data from a log file, I use "textscan", which yields an array of cells, e.g.
my_data_string = {'1.11'; '2.22'; '3.33'};
Now I want to convert all strings simultaneously to numbers.
How can I achieve this without using a for loop?
If I use the following approach,
my_data_number = textscan([my_data_string{:}], '%f'); % vector bracket causes "faulty" combined string
my_data_number = my_data_number{1,1}; % conversion of cell array to number array
my_data_number =
1.1120
0.2230
0.3300
the numbers are read incorrect because of the use of vector brackets inside the textscan command. This causes the strings to be all concanated without break, which then messes up the textscan command.
[my_data_string{:}]
ans =
'1.112.223.33'
I experimented with different brackets and vector notations, but so far, I could not find a solution. I am not necessarily fixed on using textscan, but I cannot use loops.
Thanks in advance for any advice,
DH
  댓글 수: 1
Stephen23
Stephen23 2019년 7월 10일
Why not simply:
>> my_data_string = {'1.11'; '2.22'; '3.33'};
>> num_vec = str2double(my_data_string)
num_vec =
1.11
2.22
3.33
?

댓글을 달려면 로그인하십시오.

채택된 답변

madhan ravi
madhan ravi 2019년 7월 9일
V = regexp(my_data_string,'\d+[\.]?\d*','match','once');
Wanted = str2double(V)
% or
Wanted = str2double(my_data_string) % if the data appears exactly like shown in the example
  댓글 수: 4
Stephen23
Stephen23 2019년 7월 10일
No need for the square brackets:
'-?\d+\.?\d*'
Optional positive sign:
'[+-]?\d+\.?\d*'
madhan ravi
madhan ravi 2019년 7월 10일
Thank you Stephen :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by