フィルターのクリア

Read data with repeat counts

2 ビュー (過去 30 日間)
Geetartha Dutta
Geetartha Dutta 2023 年 10 月 6 日
回答済み: Voss 2023 年 10 月 6 日
I have a data file containing numbers with repeat counts denoted by asterisk of the following format: 750.013 2*748.943 2*748.221 ... which is equivalent to 750.013 748.943 748.943 748.221 748.221 ... How can I read this data into a vector? That is, how can I take into account the repeat count operator (*) while reading the data?

採用された回答

Voss
Voss 2023 年 10 月 6 日
str = fileread('file.txt')
str = '750.013 2*748.943 2*748.221'
C = regexp(regexp(str,'\s+','split'),'\*','split');
idx = cellfun(@isscalar,C);
C(idx) = cellfun(@(x)[{'1'} x],C(idx),'UniformOutput',false);
M = str2double(vertcat(C{:}));
V = repelem(M(:,2).',M(:,1))
V = 1×5
750.0130 748.9430 748.9430 748.2210 748.2210

その他の回答 (2 件)

Mathieu NOE
Mathieu NOE 2023 年 10 月 6 日
hello
maybe this ?
data_string = "750.013 2*748.943 2*748.221"; % data imported as string array
data_string2 = split(data_string,' ');
%% main loop
store_value = [];
for k = 1:numel(data_string2)
tmp = char(data_string2(k));
ind = strfind(tmp,"*");
if ~isempty(ind) % we have 2*748.943 data (or alike
factor = str2num(tmp(1:ind-1));
value = str2num(tmp(ind+1:end));
value_all = repmat(value,[factor 1]);
store_value = [store_value;value_all];
else % we have a single value
store_value = [store_value;str2num(tmp)];
end
end
store_value
store_value = 5×1
750.0130 748.9430 748.9430 748.2210 748.2210
  1 件のコメント
Dyuman Joshi
Dyuman Joshi 2023 年 10 月 6 日
@Mathieu NOE, rather than growing the output dynamically, a better approach would be to preallocate according to the size of data_string2, find and store the number before asterisk for each element (if it does not exist, assign 1) and then use repelem on the unique elements.

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


Les Beckham
Les Beckham 2023 年 10 月 6 日
Here is one approach.
data_strings = ["750.013"; "2*748.943"; "2*748.221"] % sample input data
data_strings = 3×1 string array
"750.013" "2*748.943" "2*748.221"
iData = 1;
for iStr = 1:numel(data_strings)
if contains(data_strings(iStr), "*")
tmp = split(data_strings(iStr), "*");
rpt = str2double(tmp(1));
data(iData:(iData + rpt - 1)) = str2double(tmp(2));
else
rpt = 1;
data(iData) = str2double(data_strings(iStr));
end
iData = iData + rpt;
end
disp(data)
750.0130 748.9430 748.9430 748.2210 748.2210

カテゴリ

Help Center および File ExchangeImport, Export, and Conversion についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by