Reordering data based on a separate cell array
1 回表示 (過去 30 日間)
古いコメントを表示
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 件のコメント
Bob Thompson
2018 年 3 月 6 日
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.
採用された回答
Jos (10584)
2018 年 3 月 6 日
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.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Matrices and Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!