OpenFOAM Matlab Force Data Loader

I had a need to load some OpenFOAM force data into MATLAB recently and for my future conveniance I wrapped the import commands into a simple to use function to speed future loads.

function [data, structNames] = foamForceLoader(fname)
%FOAMFORCELOADER Load OpenFOAM force data parsing by parentheses groups
%   OpenFOAM dumps its force data in a formatted manner but the extensive
%   use of parenthesis groups makes hard work for standard text readers.
%   This function takes the input data file and returns a structure based
%   on the names given in the file.  Comments prefixed by "#" are ignored
%   and the last comment line in the header will be parsed for the
%   structure names.
%
%   This should also work with moment files that use similar rules.
%
%   Input/s:
%       -) fname: the name of the file to read.
%
%   Output/s:
%       -) data: the data array from parsing the file.
%       -) headers: the header text arrays
%
%   Dr Peter Brady <[email protected]>
%   2017-05-11

% Attempt to open the file and check for errors
fid = fopen(fname, 'r');
if (fid == -1)
error('FFL:fopen', 'Unable to open: %s', fname)
end

%% Parse the header rows:
lineBuffer = fgetl(fid);
while (lineBuffer ~= -1)
if (strcmp(lineBuffer(1), '#'))
previousLine = lineBuffer;
lineBuffer = fgetl(fid);
else
break;
end
end

% Parse the line to extract the structure names but drop the leading "#"
structNames = parseLineToChar(previousLine(2:1:end));

%% Parse the Data Lines
% First do a very quick line count to pre-allocate arrays
dataRaw = textscan(fid, '%f (%f %f %f) (%f %f %f) (%f %f %f)',...
'CommentStyle', '#');
data = cell2mat(dataRaw);

%% Be nice and close out
fclose(fid);

end

function tokens = parseLineToChar(charsToParse)
tokens = strings(0);
remain = charsToParse;
while (remain ~= "")
% Get the next token:
[token, remain] = strtok(remain); %#ok<STTOK>

% Strip "(" and ")" characters
if (token(1) == "(")
token = token(2:1:end);
end
if (token(end) == ")")
token = token(1:1:end-1);
end

% Append to our data array:
tokens = [tokens; token]; %#ok<AGROW>
end
end

Finally, thanks for reading this article and please leave a comment below. If you are interested in being updated when similar items are posted then either subscribe via RSS or sign up to my mailing list below.

Site Footer