问题描述
在MATLAB中,我试图在一个单元格数组上执行一个函数,但是运气不佳.我想创建一个cellfun
来检查str2double
是否返回NaN
值,然后对不是NaNs
的值执行str2double
.我正在尝试在其中使用带有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.
如Dan所指出的,如果您想在适当的位置更改单元格数组,请使用
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匿名函数,如果其他的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!