0

I have a cell array 25 x 2 that contains names and codes, called 'names'. The codes are numeric. I have another cell 40 x 4 called 'data'.

One column in the cell 'data' contains a numeric code that can be linked to the other 'names' cell. What I was trying to do is replace the numeric codes in 'data' with the corresponding name from the 'names' cell.

I was looking at converting the numeric code field to a string, line below. Then use the strrep function I believe I would have to create a loop to replace all the strings. Is there a better way of doing this task? Is a loop required?

 num2str(cell2mat(data(:,1)));

1 Answer 1

3

You can do this using ismember, however ismember won't work on a cell array of numbers hence I have used cell2mat to convert them to numeric vectors first.

names = {'A', 1; 'B', 2; 'C', 3};
data = {1, 1, 'a'; 2, 2, 'b'; 1, 1, 'c'; 1, 1, 'd'; 3, 3, 'e'};

[~, ind] = ismember(cell2mat(data(:,1)), cell2mat(names(:,2)))
data(:,1) = names(ind)

You can actually make use of comma separated lists to get rid of the cell2matcalls as follows:

[~, ind] = ismember([data{:,1}], [names{:,2}])
Sign up to request clarification or add additional context in comments.

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.