Search code examples
matlabmatchcell-array

replacing values in a cell array for matching values from another


There is a cell array in MATLAB

B = 

    [ 1708]    [ 2392]    '+'
    [ 3394]    [ 3660]    '+'
    [ 5490]    [ 5743]    '+'
    [ 7555]    [ 7809]    '-'
    [ 9256]    [ 9509]    '-'
    [12878]    [15066]    '-'
    [16478]    [17458]    '-'

and another cell array

C =

[4]
[7]
[1]
[6]
[2]
[5]
[3]

I want to replace the values in C with the values in B{...,3} such that C becomes

C = 

    '-'
    '-'
    '+'
    '-'
    '+'
    '-'
    '+'

How can I do that in MATLAB? I currently did this but got error

>> C(C == 'x') = B
Undefined function 'eq' for input arguments of type 'cell'.

Solution

  • You could try

    C = cellfun(@(x)B(x,3),C);
    

    This addresses the problem you were seeing with C no longer being a cell array - note the subtle difference between B{} and B().