How do I compare the order of rows in cell array with a matrix?
Show older comments
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
on 11 Dec 2022
0 votes
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
on 11 Dec 2022
the cyclist
on 11 Dec 2022
I'm unclear on the re-ordering of split_points_rounded, because it has 25 ids, but there are only 5 ids in valid_high_IDs.
Was valid_high_IDs supposed to contain all 25 ids, but (possibly) in a different order? Or did you want to extract only the rows from split_points_rounded that have ids in valid_high_IDs (and then sort them accordingly)?
Also, the split_points_rounded array you uploaded is not a cell array. It is a numeric array. Was that intentional, or did you mean for it to also be a cell array?
These details are all important to get the syntax right, to solve your problem. Setting everything up, and clearly stating the steps you need to do, are exactly how to solve this problem. I expect that if you wrote these steps down clearly and carefully, you would actually be able to solve this yourself.
lil brain
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,:)
Categories
Find more on Logical 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!