Borrar filtros
Borrar filtros

Rearranging an array by collecting values

2 visualizaciones (últimos 30 días)
Amandeep
Amandeep el 26 de Ag. de 2011
Hi, I have a very similar problem:
I'm trying to rearrange the following:
F = [1 16; 2 55; 2 61; 2 66; 2 68; . ...... 10 57];
to look like:
[1 16 0 0 0; 2 55 61 66 68; ...... 10 57 0 0 0];
and, from reading posts in newsgroups regarding the same problem, I used accumarray to get the following:
p = diff(F(:,1))~=0; q = find(F); p(q) = -diff([0;q]); p = cumsum([2;p+1]);
G = accumarry(p,F(:,2));
G = [0; 16; 0; 55; 61; 66; 68; ..... 0; 57]
and I was wondering what to do to get the matrix looking the way I want?
Thanks

Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 26 de Ag. de 2011
variant
c = accumarray(F(:,1),F(:,2),[],@(x){x});
cw = c(~cellfun('isempty',c))
cl = cellfun('length',cw);
n = numel(cw);
G = zeros(n,max(cl)+1);
lh = unique(F(:,1));
for i1 = 1:n
G(i1,1:cl(i1)+1) = [lh(i1) cw{i1}' ];
end
variant 2
F = sortrows(F,1);
[a bf] = unique(F(:,1),'first');
[~, bl] = unique(F(:,1),'last');
n = bl-bf + 1;
n1 = numel(a);
g1 = zeros(n1,max(n));
for i1 = 1:n1
g1(i1,1:n(i1)) = F(bf(i1):bl(i1),2)';
end
G = [a g1]
variant 3
F = sortrows(F,1);
t1 = [true;diff(F(:,1))~=0];
n2 = find(t1);
N = diff([n2;n2(end)+1]);
c = mat2cell(F(:,2),N,1);
m = numel(N);
g1 = zeros(n1,max(N));
for i1 = 1:m
g1(i1,1:N(i1)) = c{i1}';
end
G = [F(t1,1), g1]
more variant
F = sortrows(F,1);
t1 = [true;diff(F(:,1))~=0];
L = cumsum(t1);
S = regionprops(L, 'PixelIdxList','Area');
m = numel(S);
g1 = zeros(m,max([S.Area]));
for i1 = 1:m
g1(i1,1:S(i1).Area) = F(S(i1).PixelIdxList,2)';
end
G = [unique(F(:,1)) g1];
more (2) variant
F = sortrows(F);
t1 = [true;diff(F(:,1))~=0];
t2 = cumsum(~t1)+1;
t2(t1) = 1;
G = [F(t1,1) accumarray([cumsum(t1) t2],F(:,2))];

Más respuestas (0)

Categorías

Más información sobre Biotech and Pharmaceutical en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by