extract the smallest value out of a cell array with numbers and strings in matlab

One way to do this is to first filter out any non-numeric values from your cell array using the cellfun function, and then use the min function to determine the smallest number. Here's an example:

main.m
% Example cell array
C = {'foo', 42, 'bar', -10, 'baz', 0};

% Filter out non-numeric values
nums = cell2mat(cellfun(@(x) isnumeric(x) && isscalar(x), C, 'UniformOutput', false));
filtered = C(nums);

% Find the smallest number
smallest = min(cell2mat(filtered));
264 chars
10 lines

In this example, nums is a logical array that is true for any element of C that is both numeric and scalar. The cellfun call applies a function that checks whether each element of C is numeric and scalar, and returns a scalar logical array. The cell2mat call then converts this logical array to a numeric array. Finally, we use this array to index into C and extract only the numeric elements.

Note that this assumes there is at least one numeric value in the cell array. If there are only non-numeric values, cell2mat will throw an error. In that case, you might want to add some error handling to test for this case.

related categories

gistlibby LogSnag