Matlab匿名函数如果其他 [英] Matlab Anonymous Function If Else

查看:27
本文介绍了Matlab匿名函数如果其他的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 MATLAB 中,我尝试在元胞数组上执行函数,但运气不佳.我想创建一个 cellfun 来检查 str2double 是否返回 NaN 值,然后对这些值执行 str2double不是 NaNs.我正在尝试使用带有 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?

推荐答案

您可以使用逻辑索引:

x = {'1', 'NaN', '2', 'NaN'}
y = str2double(x(~isnan(str2double(x))))

y =
     1     2

这会调用 str2double 两次,因此如果您必须执行一百万次,它的运行速度可能会有点慢.

This calls str2double twice, so it may run a little slow if you have to do it a million times.

正如丹指出的那样,如果你想改变单元格数组,请使用

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

这篇关于Matlab匿名函数如果其他的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆