Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 699
Lererferler Avatar asked Dec 24 '22 06:12

Lererferler


2 Answers

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);
like image 122
user1656671 Avatar answered Dec 28 '22 08:12

user1656671


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))))
like image 28
gariepy Avatar answered Dec 28 '22 09:12

gariepy