Arrange array elements in 1st column w.r.t corresponding values in 2nd column
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Argo Chakraborty
el 15 de Jun. de 2021
Comentada: Argo Chakraborty
el 15 de Jun. de 2021
Hi,
I have an array like this:
A=[1 9
1 14
3 11
5 13
7 15
9 17
11 19
14 21]
I want to arrange the elements like:
[ 1 3 5 7
9 11 13 15
14 19 0 0
17 0 0 0
21 0 0 0]
The logic is :
For element '1': 9 &14 is corresponding to 1 and then 17 & 21 is corresponding to 9 & 14.So I need 1,9,14,17 & 21 in one column.
Similarly, for '3' : 11 is corresponding to 3 and 19 is corresponding to 11. So, 3, 11 &19 in second column
And so on.
0 comentarios
Respuesta aceptada
Stephen23
el 15 de Jun. de 2021
A = [1,9;1,14;3,11;5,13;7,15;9,17;11,19;14,21]
B = myfun(A)
function out = myfun(inp)
out = [];
while numel(inp)
vec = recfun(inp(1),inp(1));
out(1:numel(vec),end+1) = vec;
end
%
function vec = recfun(vec,val)
idx = find(inp(:,1)==val);
vec = [vec(:);inp(idx,2)];
for k = numel(idx):-1:1
tmp = inp(idx(k),2);
inp(idx(k),:) = [];
vec = recfun(vec,tmp);
end
end
end
Más respuestas (1)
Sailesh Kalyanapu
el 15 de Jun. de 2021
Hi,
One approach to do that would be to first create a Hash-table like structure from the given data.
%%% Create two variables Keys and Values
%%% Consider a number pair to be represented as (a,b)
%%% Keys contain all possible unique a's in the given input.
%%% ith row of Values corresponds to all b's related to a directly.
M = containers.Map(Keys,Values);
Once the Hash-table is populated, you could iterate and create columns in the result matrix by taking the first key and appending the values of that key to the values of the elements in the valueset taken as key recursively. The elements once considered in recursion can be deleted from Hash-table keys and once the end of recursion is reached the process is repeated with the next available key in the Hash-table.
Ver también
Categorías
Más información sobre Dictionaries 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!