Lererferler
Lererferler

Reputation: 297

Matlab Anonymous Function If Else

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?

Upvotes: 4

Views: 2013

Answers (3)

QT-1
QT-1

Reputation: 996

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);

Upvotes: 6

Dan
Dan

Reputation: 45752

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)

Upvotes: 1

gariepy
gariepy

Reputation: 3674

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))))

Upvotes: 3

Related Questions