replace specific commas using strrep

2 ビュー (過去 30 日間)
Lukas Netzer
Lukas Netzer 2021 年 8 月 5 日
コメント済み: Stephen23 2021 年 8 月 6 日
I converted my data:
'[[0, 145, 0], [145, 169, 1], [169, 1693, 3], [1693, 1708, 1], [1708, 2729, 3], [2729, 2779, 0]]'
using str2num.
Now I can use strrep to remove certain characters. I want to replace commas outside of the square brackets with semicolons and then remove all square brackets.
I know how to remove the brackets, but am not sure how to replace certain commas and leave the others. That's what I would use to remove the brackets:
b=strrep(data,']','');
b=strrep(data,'[','');
The final output should look like that:
'0, 145, 0; 145, 169, 1; 169, 1693, 3; 1693, 1708, 1; 1708, 2729, 3; 2729, 2779, 0'
Thank you for your help!

採用された回答

Scott MacKenzie
Scott MacKenzie 2021 年 8 月 5 日
編集済み: Scott MacKenzie 2021 年 8 月 5 日
In stages, to show the possibilities...
s1 = '[[0, 145, 0], [145, 169, 1], [169, 1693, 3], [1693, 1708, 1], [1708, 2729, 3], [2729, 2779, 0]]'
s1 = '[[0, 145, 0], [145, 169, 1], [169, 1693, 3], [1693, 1708, 1], [1708, 2729, 3], [2729, 2779, 0]]'
s2 = strrep(s1, '],', '];')
s2 = '[[0, 145, 0]; [145, 169, 1]; [169, 1693, 3]; [1693, 1708, 1]; [1708, 2729, 3]; [2729, 2779, 0]]'
s3 = strrep(s2, ']', '')
s3 = '[[0, 145, 0; [145, 169, 1; [169, 1693, 3; [1693, 1708, 1; [1708, 2729, 3; [2729, 2779, 0'
s4 = strrep(s3, '[', '')
s4 = '0, 145, 0; 145, 169, 1; 169, 1693, 3; 1693, 1708, 1; 1708, 2729, 3; 2729, 2779, 0'
  1 件のコメント
Lukas Netzer
Lukas Netzer 2021 年 8 月 5 日
thank you! :)

サインインしてコメントする。

その他の回答 (1 件)

Stephen23
Stephen23 2021 年 8 月 5 日
編集済み: Stephen23 2021 年 8 月 5 日
"I converted my data... using str2num."
Although your descriptiion is unclear, I guess that your goal to convert text data into numeric data. In that case, don't waste time fiddling around with strings (or for that matter, using STR2NUM which hides evil EVAL inside):
S = '[[0, 145, 0], [145, 169, 1], [169, 1693, 3], [1693, 1708, 1], [1708, 2729, 3], [2729, 2779, 0]]';
M = sscanf(S(2:end),'[%f,%f,%f], ',[3,Inf]).'
M = 6×3
0 145 0 145 169 1 169 1693 3 1693 1708 1 1708 2729 3 2729 2779 0
Or
M = jsondecode(S)
M = 6×3
0 145 0 145 169 1 169 1693 3 1693 1708 1 1708 2729 3 2729 2779 0
  2 件のコメント
Lukas Netzer
Lukas Netzer 2021 年 8 月 6 日
Hi thanks for your answer - above doesn't seem to work, as my data may be different then presented. I have attached the .mat-file.
Stephen23
Stephen23 2021 年 8 月 6 日
@Lukas Netzer: was the data provided to you in a .mat file? If not, please upload the original data file.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeString についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by