matlab - Making a struct from a string containing matrices and its names -
i have text file containing uint8 data this:
[0, 18, 121] bl [0, 19, 12] gt [24, 19, 22] apa [0, 18, 1] bl [24, 19, 22] apa bpa [1, 2, 3] apa
what want struct, a
, fields containing data as:
a.bl= [0, 18, 121; 0, 18, 1 ]; a.gt = [0, 19, 12]; a.apa = [24,19,22]; a.apa_bpa = [24,19, 22] or a.apabpa= [24, 19, 22]
so above example shows find multiple instances of matrix , stack them one. if there space in name, remove space or replace underscore.
until now, have:
a = importdata('file.txt');
which creates cell array (20,000 x 1 original data) containing data. know names of matrices text file have. tried differentiate matrices following gives me cell containing matrices , name:
a(~cellfun(@isempty, strfind(a,'bl')))
how proceed? or simpler solution problem more speed?
i use textscan
instead of importdata
in case, since you're dealing mixed data types:
fid = fopen('file.txt'); data = textscan(fid, '[%d%d%d%s', 'delimiter', ',]', 'collectoutput', true); fclose(fid); values = data{1}; fields = data{2};
which gives following results in values
, fields
:
values = 6×3 int32 matrix 0 18 121 0 19 12 24 19 22 0 18 1 24 19 22 1 2 3 fields = 6×1 cell array 'bl' 'gt' 'apa' 'bl' 'apa bpa' 'apa'
now can replace spaces in fields
underscores using strrep
, find unique strings unique
, number of repeats of each string accumarray
, sort rows of values
match list of unique field names, , group rows of values
using mat2cell
:
[fields, ~, index] = unique(strrep(fields, ' ', '_')); counts = accumarray(index, 1); [~, sortindex] = sort(index); values = mat2cell(values(sortindex, :), counts);
now can put structure using cell2struct
:
s = cell2struct(values, fields) s = struct fields: apa: [2×3 int32] apa_bpa: [24 19 22] bl: [2×3 int32] gt: [0 19 12]
wiki
Comments
Post a Comment