简体   繁体   English

Matlab匿名函数如果其他

[英]Matlab Anonymous Function If Else

In MATLAB I am trying to do a function on a cell array, but am not having much luck.在 MATLAB 中,我试图在元胞数组上执行一个函数,但运气不佳。 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 .我想创建一个cellfun来检查str2double是否返回NaN值,然后对不是NaNs的值执行str2double I'm trying to use an anonymous function with an IF Else sort of statement in it but not really getting anywhere.我正在尝试使用带有 IF Else 类型语句的匿名函数,但实际上并没有得到任何结果。 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 实现:

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.如果条件计算结果为真,则函数返回真值,否则返回 false_falue。

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.这是一个有用的过滤器,可以应用于从 csv 或 excel 文件读取的单元格,以便它们可以用作数字数组。 For example on an arrary Ra that was read using xlsread:例如,在使用 xlsread 读取的数组 Ra 上:

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.这会调用str2double两次,因此如果您必须执行一百万次,它的运行速度可能会有点慢。

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

You might be able to get this to work using Loren Shure's inline conditional:您可以使用Loren Shure 的内联条件来实现它:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM