In MATLAB I am trying to do a function on a cell array, but am not having much luck. I would like to create a cellfun
which checks whether str2double
returns NaN
values and then perform the str2double
on the values which aren't NaNs
. I'm trying to use an anonymous function with an IF Else sort of statement in it but not really getting anywhere. Here is what I have come up with so far:
x = cellfun(@(x)~isnan(str2double(x)),str2double(x))
However it doesn't work, could anybody help me out?
Here is a nice, compact and working iif implementation:
iif = @(varargin) varargin{3-(varargin{1}>0)}
Usage:
iif(condition, true_value, false_value)
The function returns true value if the condition evaluates to true and the false_falue otherwise.
Here is a useful filter that can be applied on cells read from csv or excel file so they can be used as a numeric array. For example on an arrary Ra that was read using xlsread:
numeric_array = cellfun( @(x) iif(isnumeric(x) & ~isempty(x),x,NaN), Ra);
You could use logical indexing:
x = {'1', 'NaN', '2', 'NaN'}
y = str2double(x(~isnan(str2double(x))))
y =
1 2
This calls str2double
twice, so it may run a little slow if you have to do it a million times.
EDIT: as pointed out by Dan, if you want to change the cell array in place, use
x{~isnan(str2double(x))} = str2double(x(~isnan(str2double(x))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With