Partitioning a vector of doubles into cells using a second vector to index
조회 수: 1 (최근 30일)
이전 댓글 표시
Hi all,
I would like to partition a vector of numbers into separate sub-cells, using a second vector as a list of indices. See the example below:
vectorContents = 1:5;
indexingVector = [1 1 1 2 2];
I'd like the output to be a cell array that looks like
storeCell = {[1 1 1],[2 2]}
Is there a way to achieve this using deal and other parallelized functions to avoid a for loop? My current implementation looks like this:
vectorContents = 1:5;
indexingVector = [1 1 1 2 2];
uniqueInds = unique(indexingVector);
storeCell = cell(numel(uniqueInds),1);
for ii = 1:numel(uniqueInds)
currInd = uniqueInds(ii);
currLogic = indexingVector == currInd;
storeCell{ii} = vectorContents(currLogic);
end
Thanks in advance!
댓글 수: 0
채택된 답변
추가 답변 (1개)
Pavl M.
2024년 10월 17일
편집: Pavl M.
2024년 10월 17일
clc
clear all
close all
vectorContents = 1:7
indexingVector = [1 1 1 2 2 3 3]
uniqueInds = unique(indexingVector)
storeCell = cell(numel(uniqueInds),1)
%Solution with no loops:
tic
%Form vector of distinct values repetitions (acc to your custom logic):
vec = [3 2 2]; % 1D vector
storeCell = mat2cell(vectorContents,1,vec)
toc
%Ver of Stephen23 measurements
tic
C = accumarray(indexingVector(:),vectorContents(:),[],@(vectorContents){vectorContents.'})
toc
tic
C = arrayfun(@(n)vectorContents(n==indexingVector),1:max(indexingVector),'Uni',0) % probably the slowest
toc
tic
C = groupsummary(vectorContents(:),indexingVector(:),@(indexingVector){indexingVector.'})
toc
%Solution with 1 loops:
tic
for ii = 1:numel(uniqueInds)
currInd = uniqueInds(ii);
currLogic = indexingVector == currInd;
storeCell{ii} = vectorContents(currLogic)
end
toc
%Constructed by P.Mazniker
%Constructed from needing help code by
%https://join.skype.com/invite/oXnJhbgys7oW
%https://independent.academia.edu/PMazniker
%+380990535261
%https://diag.net/u/u6r3ondjie0w0l8138bafm095b
%https://github.com/goodengineer
%https://orcid.org/0000-0001-8184-8166
%https://willwork781147312.wordpress.com/portfolio/cp/
%https://www.youtube.com/channel/UCC__7jMOAHak0MVkUFtmO-w
%https://nanohub.org/members/130066
%https://pangian.com/user/hiretoserve/
%https://substack.com/profile/191772642-paul-m
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!