How do I compare the order of rows in cell array with a matrix?

7 views (last 30 days)
Hi,
I have a numerical array called split_points_rounded and a cell array called valid_high_IDs. The first column of split_points_rounded and the first row of valid_high_IDs should theoretically be in the same order (these are participant IDs from a study).
I am looking for a way to
1) check if they are in the same order and
2) re-order the rows in split_points_rounded according to the order in valid_high_IDs and save that in a new cell array if the two are not already in the same order.
Help is much appreciated!

Answers (1)

the cyclist
the cyclist on 11 Dec 2022
You can use the ismember function to both test that the values of one array are present in the other one, and also to get their locations in that array. You can then use the output to see if they are in the sorting order you want.
  4 Comments
lil brain
lil brain on 11 Dec 2022
Apologies for that.
1) valid_high_IDs is supposed to contain 5 and split_points_rounded should only contain 5 as well. I accidentally uplaoded a different version that contains 25 (the real number of participants).
2) Yes sorry this was supposed to be a numerical array.
I have updated the question and the files. Would be very grateful if you could show me some code.
Thank you!
the cyclist
the cyclist on 11 Dec 2022
Your uploaded data are not a great example, since they are already correctly sorted, but I believe this does what you want.
% % Load local file
% load('split_points_rounded.mat','split_points_roundedCopy')
% load('valid_high_IDs.mat','valid_high_IDs')
% Load from web
load(websave('f1','https://www.mathworks.com/matlabcentral/answers/uploaded_files/1227412/split_points_rounded.mat'))
load(websave('f2','https://www.mathworks.com/matlabcentral/answers/uploaded_files/1226807/valid_high_IDs.mat'))
% Convert the cell array with character arrays into a numeric array
idOrder = cellfun(@str2double,valid_high_IDs);
% Find the locations of one array in the other
[~,loc] = ismember(idOrder,split_points_roundedCopy(:,1));
% Sort accordingly
split_points_rounded_reordered = split_points_roundedCopy(loc,:)
split_points_rounded_reordered = 5×5
1.0e+03 * 1.3110 0.1284 0.1380 0.1944 0.6174 1.4110 0.0756 0.0924 0.1554 0.9780 2.1110 0.0624 0.0684 0.1242 0.1524 2.2110 0.0666 0.0714 0.0834 0.1554 2.3110 0.0672 0.0786 0.1218 0.4326

Sign in to comment.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!