how to test if a value in a cell array matches a vaule in matlab

To test if a value in a cell array matches a value in matlab, one can use the ismember function or a for loop along with string comparison. Here are examples of both approaches:

Using ismember function:

main.m
% define the cell array
myCellArray = {'apple', 'banana', 'orange', 'pear'};

% define the value to check
valueToCheck = 'orange';

% check if the value is in the cell array using ismember
isValueInArray = ismember(valueToCheck, myCellArray);
243 chars
9 lines

Using for loop and string comparison:

main.m
% define the cell array
myCellArray = {'apple', 'banana', 'orange', 'pear'};

% define the value to check
valueToCheck = 'orange';

% loop over each element of the cell array and check if the value matches
isValueInArray = false;
for ii = 1:numel(myCellArray)
    if strcmp(valueToCheck, myCellArray{ii})
        isValueInArray = true;
        break; % value found, stop looping
    end
end
391 chars
15 lines

gistlibby LogSnag