Tom
Tom

Reputation: 121

find and replace values in cell array

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!

Upvotes: 4

Views: 11147

Answers (1)

gnovice
gnovice

Reputation: 125874

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

Upvotes: 3

Related Questions