Skip to content

Instantly share code, notes, and snippets.

@michael-nischt
Created July 19, 2012 00:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michael-nischt/3139857 to your computer and use it in GitHub Desktop.
Save michael-nischt/3139857 to your computer and use it in GitHub Desktop.
creating record like data structures from arrays grouped by an index cell
function [ grouped ] = grouped( indices, varargin )
if iscell(indices)
I = indices;
else
I = grouped_indices( indices );
end
if isempty(varargin)
grouped = I;
return
end
names = varargin(1:2:end);
values = varargin(2:2:end);
%grouped(length(I)) = struct;
%for i=1:length(I)
for i=length(I):-1:1
elem = struct;
for j=1:length(names)
name = names{j};
value = submat( values{j}, I{i} );
elem = setfield(elem,name,value) ;
end
grouped(i) = elem;
end
end
% O(n)
function [ I ] = grouped_indices( indices )
B = unique(indices);
I = cell(1, length(B));
for i=1:length(B)
I{i} = find(indices == B(i));
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment