Arrange array elements in 1st column w.r.t corresponding values in 2nd column
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Argo Chakraborty
il 15 Giu 2021
Commentato: Argo Chakraborty
il 15 Giu 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 Commenti
Risposta accettata
Stephen23
il 15 Giu 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
Più risposte (1)
Sailesh Kalyanapu
il 15 Giu 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.
Vedere anche
Categorie
Scopri di più su Dictionaries in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!