parse an ini file and turn it into a struct in matlab

Here's an example function that parses an ini file and returns a struct in Matlab:

main.m
function s = read_ini_file(file_path)
    % Read the ini file into a cell array of strings
    ini_lines = readlines(file_path);

    s = struct();
    current_section = '';

    % Loop through each line of the ini file
    for i = 1:length(ini_lines)
        line = ini_lines{i};
        line = strtrim(line); % Remove leading/trailing spaces

        % Ignore blank lines and comments
        if isempty(line) || line(1) == ';' || line(1) == '#'
            continue
        end

        % Check if the line defines a section
        if line(1) == '[' && line(end) == ']'
            current_section = strtrim(line(2:end-1));
            continue
        end

        % Parse key-value pairs
        [key, value] = strtok(line, '=');
        key = strtrim(key);
        value = strtrim(value(2:end)); % Remove '='

        % Convert value to numeric if possible
        if ~isnan(str2double(value))
            value = str2double(value);
        end

        % Add key-value pair to current section of struct
        if isfield(s, current_section)
            s.(current_section).(key) = value;
        else
            s.(current_section) = struct(key, value);
        end
    end
end
1188 chars
42 lines

This function reads the ini file into a cell array of strings, then loops through each line and parses it to extract the section name, key-value pairs, and values. It then stores the results in a struct, with each section represented as a nested struct within the main struct.

Here's an example ini file:

main.m
; comments start with a semicolon or hash
[section1]
key1 = value1
key2 = 42
key3 = 3.14
[section2]
key1 = foo
key2 = bar
122 chars
9 lines

You can call the function with the file path as an argument:

main.m
s = read_ini_file('config.ini');
disp(s.section1.key1); % prints 'value1'
disp(s.section1.key2); % prints 42
disp(s.section2.key2); % prints 'bar'
147 chars
5 lines

gistlibby LogSnag