フィルターのクリア

Grep a numeric array from a text file

8 ビュー (過去 30 日間)
fsgeek
fsgeek 2017 年 8 月 18 日
コメント済み: fsgeek 2017 年 8 月 18 日
Dear all,
I have a text file which contains numeric data enclosed with square brackets and parentheses. The data delimiter is a comma. The contents of the file look like this:
[(1, 2, 3), (4, 5, 6, 7), (8, 9)]
The values themselves are arbitrary; I chose ascending integers for convenience. The length of each set of values enclosed by parentheses is arbitrary and could be different every time the file is written. The parentheses always enclose at least one value.
I would like to read the text file so that I get an array like this:
values =
1 2 3 4 5 6 7 8 9
whos values
Name Size Bytes Class Attributes
values 1x9 72 double
So far, I have loaded the text file so that I have a structure containing the text data. I am having trouble converting the data to an array, but I'm guessing that I need regexp().
This is what I've tried:
fileName = sprintf('..\data.dat', pwd);
data= importdata(fileName, ',');
data= cell2mat(data);
% Arrange the sub (node) IDs
values = regexp(data, '), (', 'split');
This does something vaguely close to what I need, but it's not correct. I have searched the forums but can't find anything similar to this text format.
Any help would be greatly appreciated, thanks!
Best regards,
Louis Vallance
  2 件のコメント
Stephen23
Stephen23 2017 年 8 月 18 日
What do you expect this to do?:
sprintf('..\data.dat', pwd);
fsgeek
fsgeek 2017 年 8 月 18 日
Oops, that was a typo :) I don't have a problem opening the file so that line can be ignored.

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

採用された回答

Stephen23
Stephen23 2017 年 8 月 18 日
編集済み: Stephen23 2017 年 8 月 18 日
>> str = '[(1, 2, 3), (4, 5, 6, 7), (8, 9)]';
>> str2double(regexp(str,'\d+','match'))
ans =
1 2 3 4 5 6 7 8 9
and to read the data from the file you could simply use fileread:
str = fileread(...)

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by