Partitioning a vector of doubles into cells using a second vector to index
1 view (last 30 days)
Show older comments
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 Comments
Accepted Answer
More Answers (1)
Pavl M.
on 17 Oct 2024
Edited: Pavl M.
on 17 Oct 2024
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
See Also
Categories
Find more on Loops and Conditional Statements 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!