假设我有以下数组:
a = {1; 'abc'; NaN}
Run Code Online (Sandbox Code Playgroud)
现在我想找出哪些索引包含NaN,以便我可以用''(空字符串)替换它们.
如果我用cellfun用isnan,我得到一个无用的输出
cellfun(@isnan, a, 'UniformOutput', false)
ans =
[ 0]
[1x3 logical]
[ 1]
Run Code Online (Sandbox Code Playgroud)
那我该怎么做呢?
Rod*_*uis 11
事实上,正如你发现自己,这可以通过
a(cellfun(@(x) any(isnan(x)),a)) = {''}
Run Code Online (Sandbox Code Playgroud)
分解:
Fx = @(x) any(isnan(x))
Run Code Online (Sandbox Code Playgroud)
将返回逻辑标量,无论x是标量还是向量.在内部使用此功能cellfun将消除对以下需求'UniformOutput', false:
>> inds = cellfun(Fx,a)
inds =
0
0
1
Run Code Online (Sandbox Code Playgroud)
这些可以用作原始数组的索引:
>> a(inds)
ans =
[NaN]
Run Code Online (Sandbox Code Playgroud)
这反过来允许分配这些指数:
>> a(inds) = {''}
a =
[1]
'abc'
''
Run Code Online (Sandbox Code Playgroud)
请注意,必须对单元数组本身进行赋值.如果你不明白这一点,请阅读a(inds)和之间的区别a{inds}.
| 归档时间: |
|
| 查看次数: |
13413 次 |
| 最近记录: |