0

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'.
chappjc
  • 30,359
  • 6
  • 75
  • 132
chris
  • 190
  • 1
  • 14

3 Answers3

3

Horizontal concatenation ([]) with comma-separated list cell array output ({:}) gives a direct way to index the appropriate rows in B:

Cnew = B([C{:}],3)
chappjc
  • 30,359
  • 6
  • 75
  • 132
2

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().

Floris
  • 45,857
  • 6
  • 70
  • 122
  • That made C a 7x1 char, I need to keep it as a Cell array – chris Feb 26 '14 at 18:46
  • 3
    Use NUM2CELL around it. It would be - C = num2cell(cellfun(@(x)B{x,3},C)); – Divakar Feb 26 '14 at 18:53
  • 1
    @Divakar, please don't edit someone else's answer, even if you have a better suggestion. Leave a comment, and let the person who answered edit it if he/she feels like it. (You may edit to make it readable, typos, formatting etc., but not the content). – Stewie Griffin Feb 26 '14 at 18:54
  • @ Robert, I am still learning the etiquette of commenting here! Thanks @Floris. – Divakar Feb 26 '14 at 19:11
  • 1
    @chris see my update. Replacing the `{}` with `()` fixed the problem you were seeing. – Floris Feb 26 '14 at 19:27
1

Basic indexing, to get the elements of X in the order a=[1,3,2,4] use X(a). Indices are matrices, thus a conversion is needed, nothing else.

B(cell2mat(c),3)
Daniel
  • 36,610
  • 3
  • 36
  • 69