0

I'm trying to get used to doing things in vectors rather than looping. The question I have is I have two vectors. Vector 2 is a 64x2 cell first column contains strings the second contains numbers. I want to match Vector 1 & 2 on the string value and copy the numeric value over into a new field in Vector 1 if possible?

Vector 1            Vector 2
GHJ                 ABC        352
LMN                 GHJ        62
OPQ                 LMN        3698
                    OPQ        12

I would then like Vector 1 to look like below,

Vector 1
GHJ     62
LMN     3698
OPQ     12

Actually I guess for this problem could also be solved by deleting the row ABC from vector 2.

mHelpMe
  • 6,336
  • 24
  • 75
  • 150
  • Do you really mean you have a "field", or are these "cell matrices". Not clear from your question - but important for a useful answer. Perhaps you can show how you create `Vector1` and `Vector2` - should be just 2 lines of Matlab code? It would make answering much easier. – Floris Apr 14 '14 at 15:39
  • See http://stackoverflow.com/a/3592050/1967396 - I think you should be able to adapt the trick shown there to easily solve your problem, if you use the right way to represent `Vector2` (namely, as a `Containers.Map`) – Floris Apr 14 '14 at 15:42
  • Hi Floris - I've just updated the question. Vector 2 is a 64x2 cell. Sorry still need to learn the correct terminology. I'll check the link you just sent too. thanks – mHelpMe Apr 14 '14 at 15:44

1 Answers1

3

You can use ismember to compare two arrays. To have strings and numbers in one array you'll have to use a cell array.

A = {'ABC', 352; 'GHJ', 62; 'LMN', 3698; 'OPQ', 12}
B = {'GHJ'; 'LMN'; 'OPQ'};

matchIndex = ismember(A(:,1), B) %put your vector 2 first
matchIndex =
     0
     1
     1
     1

This will return a logial vector the length of A containing 1 (true) where the data in A is found in B. Elsewhere, it returns 0 (false). Check the documentation of ismember for more examples!
You can use this logical array for logical indexing into A

C = A(matchIndex,:);
C = 
    'GHJ'    [  62]
    'LMN'    [3698]
    'OPQ'    [  12]
Moritz
  • 48
  • 5
  • Very nice solution - some variation of this will surely be just what OP needs. – Floris Apr 14 '14 at 16:00
  • 1
    I don't think you need the 'rows' option in this case. I get a warning that the argument is ignored. Try "matchIndex = ismember(A(:,1), B)" instead. – Joe Serrano Apr 14 '14 at 16:29
  • Oh, you are right. I recently used `ismember` with a numerical array. But with the cell array 'rows' is not needed. – Moritz Apr 14 '14 at 17:46