Reordering data based on a separate cell array

조회 수: 1 (최근 30일)
Scott McLean
Scott McLean 2018년 3월 6일
댓글: Scott McLean 2018년 3월 6일
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
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)
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 CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by