check if a number is in a structure in matlab

One way to check if a number is in a structure in Matlab is to use a loop to iterate over each field of the structure and check if that field contains the number. Here's an example implementation:

main.m
function isPresent = isNumberInStruct(number, myStruct)
    % Loop through each field in the structure
    isPresent = false;  % Initialize flag
    fields = fieldnames(myStruct);
    for i = 1:numel(fields)
        fieldData = myStruct.(fields{i});
        % Check if the field contains the number
        if isnumeric(fieldData) && any(fieldData == number)
            isPresent = true;
            break;  % Exit loop early if number is found
        end
    end
end
470 chars
14 lines

This function takes two arguments: the number you're searching for and the structure you want to search in. It returns true if the number is present in the structure, and false otherwise.

Note that this implementation assumes that the structure does not have nested substructures. If it does, you'll need to modify the function to handle them appropriately.

related categories

gistlibby LogSnag