Reordering data based on a separate cell array
1 view (last 30 days)
Show older comments
I have a data array that i wish to reorder using a cell (string) array to define how data should be reordered. In other words, i need to look at the cell array, work out the necessary reordering steps for this array and then apply the same reordering steps to the data array. My first version of code is long winded, but gets it done. Looking for a much cleaner solution. Here is the code (note: new to cells and structures) to determine reordering approach:
B=cellfun(@(x) x(1:min(numel(x),2)),act_list,'un',0); %reduces strings to first two letters to distinguish them
%Now 4 arrays to get ordering
fl=[];
ex=[];
hi=[];
un=[];
for i=1:12
if B{i}=='Si' | B{i}=='St' | B{i}=='W'
fl=[fl,i];
elseif B{i}=='Ou' | B{i}=='Jo'| B{i}=='Ru' | B{i}=='Cy' | B{i}=='El'
ex=[ex,i];
elseif B{i}=='In'
hi=[hi,i];
elseif B{i}=='We'
un=[un,i];
end
end
How can i clean this up?
1 Comment
Bob Thompson
on 6 Mar 2018
fl = ismember(B{:},'Si','St','w');
ex = ismember(B{:},'Ou','Jo','Ru','Cy','El');
etc...
I don't know that ismember can check for multiple things in the way I have it set up, but basically it will give you a logic array with the locations where the conditions are met. It won't give you the specific numbers like you were making, but you can output the values based on that using something like the following:
A = random(4);
C = A(fl==1); % This will make C only values of A where fl is 1, corresponding to Si, St, and w in B.
Accepted Answer
Jos (10584)
on 6 Mar 2018
B = {'Si','W','Ou','In','We','Ru','Cy','El','St','Jo', 'In'} % example data
Collections = { {'Si','St','W'},{'Ou','Jo','Ru','Cy','El'},{'In'},{'We'}}
% engine, loop over Collections rather than over B
Loc = cellfun(@(c) find(ismember(B,c)), Collections, 'un', 0)
% fl = Loc{1}, ex = Loc{2} etc.
More Answers (0)
See Also
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!