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'.
4
  • post the code, what are the errors you are getting ? Commented Feb 26, 2014 at 18:40
  • 1
    I don't understand your code sample. Why are you comparing to x? Commented Feb 26, 2014 at 18:45
  • x is the row index of B Commented Feb 26, 2014 at 18:53
  • 1
    It makes no sense to compare to the char 'x', at least following your problem description. Commented Feb 26, 2014 at 18:55

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

I like this approach.
One-liners aren't very helpful without a little explanation... now for some links.
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().

5 Comments

That made C a 7x1 char, I need to keep it as a Cell array
Use NUM2CELL around it. It would be - C = num2cell(cellfun(@(x)B{x,3},C));
@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).
@ Robert, I am still learning the etiquette of commenting here! Thanks @Floris.
@chris see my update. Replacing the {} with () fixed the problem you were seeing.
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.