find and replace values in cell array

最后都变了- 提交于 2020-01-03 17:10:59

问题


I have a cell array like this: [...

0
129
8...2...3...4
6...4
0

I just want to find and replace specific values, but I can't use the ordinary function because the cells are different lengths. I need to replace many specific values at the same time and there is no general function about how values are replaced. However, sometimes several input values should be replaced by the same output.

so I want to say
for values 1:129
'if 0, then 9'
'elseif 1 then 50'
'elseif 2 or 3 or 4 then 61' etc...up to 129

where these rules are applied to the entire array.

I've tried to work it out myself, but still getting nowhere. Please help!


回答1:


Since your values appear to span the range 0 to 129, one solution is to add one to these values (so they span the range 1 to 130) and use them as indices into a vector of replacement values. Then you can apply this operation to each cell using the function CELLFUN. For example:

>> C = {0, 129, [8 2 3 4], [6 4], 0};  %# The sample cell array you give above
>> replacement = [9 50 61 61 61 100.*ones(1,125)];  %# A 1-by-130 array of
                                                    %# replacement values (I
                                                    %# added 125 dummy values)
>> C = cellfun(@(v) {replacement(v+1)},C);  %# Perform the replacement
>> C{:}  %# Display the contents of C
ans =
     9

ans =
   100

ans =
   100    61    61    61

ans =
   100    61

ans =
     9


来源:https://stackoverflow.com/questions/5472017/find-and-replace-values-in-cell-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!