MATLAB Answers

Arrange array elements in 1st column w.r.t corresponding values in 2nd column

1 view (last 30 days)
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.

Accepted Answer

Stephen
Stephen on 15 Jun 2021
A = [1,9;1,14;3,11;5,13;7,15;9,17;11,19;14,21]
A = 8×2
1 9 1 14 3 11 5 13 7 15 9 17 11 19 14 21
B = myfun(A)
B = 5×4
1 3 5 7 9 11 13 15 14 19 0 0 21 0 0 0 17 0 0 0
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

More Answers (1)

Sailesh Kalyanapu
Sailesh Kalyanapu on 15 Jun 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.
You can refer Map Containers to implement the same. You can also refer to this

Community Treasure Hunt

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

Start Hunting!

Translated by