MATLAB Answers


I have a cell array A and a cell array B and want to re-order info in A according to B.

Asked by GioPapas81 on 30 Apr 2018 at 17:10
Latest activity Commented on by GioPapas81 on 18 May 2018 at 10:56

I have a cell array A {1:2,1:23} and a cell array B {1,1:300}. B is the reference standard to re-order A. The cell array A {1,1:23} contains a small subset of uid information of B {1,1:300}, but in a random order. I also have geometrical information in A {2, 1:23} corresponding to A {2, 1:23} but, not included in B at all. What I want to do is to create a cell array or matrix C, with all information of A {1,1:23} contained in B, re-ordered. The re-ordering needs to follow the sequence of appearance of elements A in B (hence, the exact order the elements A appear in B sequentially re-ordered). I then need to re-order A {2,1:23} in the same way (via indexing?). Any ideas would be very much appreciated! I attach A and B.


Sign in to comment.

1 Answer

Answer by Chris Perkins on 3 May 2018 at 20:23
 Accepted Answer

Here's one approach you could use to re-order the elements of A in a new cell, C:

% Assuming A and B are already loaded into your Workspace
C = cell(size(B));
for i = 1:size(A, 2) % for each element in A
   C(find(strcmp(B, A{1,i}))) = {A{2,i}}; % Put the element from A in the right place in C
C(cellfun('isempty',C)) = []; % Remove empty elements

Here, we make C the same size as B, put every element from A in the correct place in C, and then remove the empty elements, so C ends up holding only the matches from A to B.

Note: I ran this with your data, and it appears that some uid's in A are not present in B (only 16 of the 23 elements in A were matched to indexes in B). So, in this case, C becomes a 1x16 cell.

  1 Comment

Sorry for the delay, that's true Chris. Thank you for this!

Sign in to comment.

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today