Character string to numeric vector

3 Ansichten (letzte 30 Tage)
Roderick
Roderick am 20 Sep. 2024
Bearbeitet: Stephen23 am 20 Sep. 2024
Dear all
I am extracting from a file in a for loop information in the following form: ' ( 0.0357 -0.0001 0.0051) ', which is a 1x27 char. I would like to store the three displayed numbers in a the three components of an array so I can use these figures to do mathematical operations. How could I transform them to do so in this case, keeping the minus signs that can appear for different steps of the for loop too?
  1 Kommentar
Stephen23
Stephen23 am 20 Sep. 2024
@Richard Wood: please upload an unaltered sample data file by clicking the paperclip button.

Melden Sie sich an, um zu kommentieren.

Antworten (2)

Stephen23
Stephen23 am 20 Sep. 2024
Bearbeitet: Stephen23 am 20 Sep. 2024
txt = ' ( 0.0357 -0.0001 0.0051) '
txt = ' ( 0.0357 -0.0001 0.0051) '
vec = sscanf(txt(3:end),'%f',[1,3])
vec = 1×3
0.0357 -0.0001 0.0051
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
or
vec = sscanf(strtrim(txt),'(%f%f%f',[1,3])
vec = 1×3
0.0357 -0.0001 0.0051
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>

Sameer
Sameer am 20 Sep. 2024
Hi Richard,
To extract the numbers from the string and store them in an array, you can use the "sscanf" function
Here's how you can do it:
% Example string
str = ' ( 0.0357 -0.0001 0.0051) ';
% Use sscanf to extract the numbers
numbers = sscanf(str, ' ( %f %f %f) ');
disp(numbers);
Please refer to the below MathWorks documentation link:
Hope this helps!

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by