Getting values separated by commas from a string array

95 views (last 30 days)
I have this string array:
str
113x 1
"52,884,410"
"44,878,410"
"46,896,410"
"82,941,410"
.
.
.
"130,890,415"
and I would like to extract each one of these values independently to assign a different variable to each one of them, for instance, X to the first group of numbers before the first comma, y to the group of numbers between commas, and z to the last group of numbers.
When using str2num or str2double it converts it to NaN insteas of numbers.
I used X = str2num(srt(1,:)) and I got the first one as a double [52 884 410], but don't know how to have only an array only for the first group to assign it to X taking into account all the values from the array.
  2 Comments
Cris LaPierre
Cris LaPierre on 20 Mar 2023
I think it would be easier to do somethign at the source. How is this variable created?
Luis Ricardo Rivera Goitia
This variable comes from an MQTT Topic, which at the beginning is a Table divided in three columns:
Topic, QualityOfService, Callback
Then I read the Topic directly from the MQTT Broker to obtain a timetable:
Time, Topic, Data
In the last column, I mean "Data" I have these values:
row 1 "{115,878,51}"
row2 2 "{121,80,57}"
.
.
.
row n "{56,890,47}"
So I create a new string array called:
New_Data = dataTT.Data which I used to extract the values just like you told, but before I get rid of the brackets,
str = New_Data
str = strrep(str,'{','');
str = strrep(str,'}','');
tmp = split(str,",");
current = str2double(tmp(:,1));
speed = str2double(tmp(:,2));
time = str2double(tmp(:,3));

Sign in to comment.

Accepted Answer

Cris LaPierre
Cris LaPierre on 20 Mar 2023
One way is to use split.
str = ["52,884,410"
"44,878,410"
"46,896,410"
"82,941,410"
"130,890,415"]
str = 5×1 string array
"52,884,410" "44,878,410" "46,896,410" "82,941,410" "130,890,415"
tmp = split(str,",");
x = str2double(tmp(:,1))
x = 5×1
52 44 46 82 130
y = str2double(tmp(:,2))
y = 5×1
884 878 896 941 890
z = str2double(tmp(:,3))
z = 5×1
410 410 410 410 415

More Answers (1)

Steven Lord
Steven Lord on 20 Mar 2023
You can do this with split and double.
S = ["52,884,410"
"44,878,410"
"46,896,410"
"82,941,410"]
S = 4×1 string array
"52,884,410" "44,878,410" "46,896,410" "82,941,410"
S2 = split(S, ",")
S2 = 4×3 string array
"52" "884" "410" "44" "878" "410" "46" "896" "410" "82" "941" "410"
D = double(S2)
D = 4×3
52 884 410 44 878 410 46 896 410 82 941 410
This assumes each of the elements in S contains the same number of numbers. If not split will throw an error.
T = ["123,456"; "789,012,345"]
T = 2×1 string array
"123,456" "789,012,345"
T2 = split(T, ",")
Error using split
Element 2 of the text contains 2 delimiters while the previous elements have 1. All elements must contain the same number of delimiters.

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!