I everybody,
I’m trying to parse a text file into matlab: it consists of several blocks (START_BLOCK/END_BLOCK) where are allocated strings (variable) and values (associated to the previous variables).
An example is this:
START_BLOCK_EXTREMEWIND
velocity_v1 29.7
velocity_v50 44.8
velocity_vred1 32.67
velocity_vred50 49.28
velocity_ve1 37.9
velocity_ve50 57
velocity_vref 50
END_BLOCK_EXTREMEWIND
Currently, my code is:
fid = fopen('test_struct.txt','rt');
C = textscan(fid,'%s %f32 %*[^\n]','CollectOutput',true);
C{1} = reshape(C{1},1,numel(C{1}));
C{2} = reshape(C{2},1,numel(C{2}));
startIdx = find(~cellfun(@isempty, regexp(C{1}, 'START_BLOCK_', 'match')));
endIdx = find(~cellfun(@isempty, regexp(C{1}, 'END_BLOCK_', 'match')));
assert(all(size(startIdx) == size(endIdx)))
extract_parameters = @(n)({C{1}{startIdx(n)+1:endIdx(n) - 1}});
parameters = arrayfun(extract_parameters, 1:numel(startIdx), 'UniformOutput', false);
s = cell2struct(cell(size(parameters{1})),parameters{1}(1:numel(parameters{1})),2);
s.velocity_v1 = C{2}(2);
s.velocity_v50 = C{2}(3);
s.velocity_vred1 = C{2}(4);
s.velocity_vred50 = C{2}(5);
s.velocity_ve1 = C{2}(6);
s.velocity_ve50 = C{2}(7);
s.velocity_vref = C{2}(8);
It works, but it’s absolutely static. I would rather have a code able to:
1. check the existence of blocks --> as already implemented;
2. the strings are to be taken as fields of the structure;
3. the numbers are meant to be the attributes of each field.
Finally, if there is more than one block, there should be and iteration about those blocks to get the whole structure.
It’s the first time I approach structure coding at all, so please be patient.
I thank you all in advance.
Kindest regards.
It sounds like you will want to make use of dynamic field names. If you have a struct
s, a stringfieldNamethat stores the name of a field, andfieldValwhich holds the value that you’d like to set for this field, then you can use the following syntax to perform the assignment:This MATLAB doc provides further info.
With this in mind, I took a slightly different approach to parse the text. I iterated through the text with a for loop. Although for loops are sometimes frowned upon in MATLAB (since MATLAB is optimized for vectorized operations), I think in this case it helps to make the code cleaner. Furthermore, my understanding is that if you are having to make use of
arrayfun, then replacing this with a for loop probably won’t really cause much of a performance hit, anyway.The following code will convert each block in the text to a struct with the specified fields and values. These resulting “block” structs are then added to a higher-level “result” struct.
Hopefully this answers your question… or at least provides some helpful hints.