问题
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?
回答1:
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))))
回答2:
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);
回答3:
You might be able to get this to work using Loren Shure's inline conditional:
iif = @(varargin) varargin{2 * find([varargin{1:2:end}], 1, 'first')}();
Then you can try
x = cellfun(@(y)iif(~isnan(str2double(y)), str2double(y), true, y), x, 'uni', 0)
来源:https://stackoverflow.com/questions/36867822/matlab-anonymous-function-if-else