Avoid for loop: Looping through rows of m-by-n logical array
이전 댓글 표시
Postedit: Read the comments below the accepted answer!
Is it possible to view the rows of a logical array independently without using a for-loop?
x = randi(5, 1, 10) % create 1x10 vector containing random integers between 1 & 5
y = randi(5, 1, 10)
xVals = unique(x)' % get column-vector of unique values of x
tf = x == xVals % logical array, that shows for every unique x-value, at which indices it occurs in x.
for i = 1:size(tf,1) % loop through rows of logical array
yVals(i) = {y(tf(i,:))}; % Assign all y-values that belong to one xVal-entry to one cell.
end
채택된 답변
추가 답변 (2개)
Another way,
yVals = splitapply( @(g){g(:).'}, y, findgroups(x))
Bruno Luong
2018년 4월 21일
편집: Bruno Luong
2018년 4월 21일
For older MATLAB version, this FEX might be useful SplitVec
c = SplitVec(sortrows([x;y]'),1,2)
When stable ordering of y is desired
c = SplitVec(sortrows([x;y]',1),1,2)
카테고리
도움말 센터 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!