MATLAB Answers

unique vector with restrictions

3 views (last 30 days)
Rub Ron
Rub Ron on 28 Aug 2020
Commented: the cyclist on 28 Aug 2020
Say I have these vector:
head_1=[1 6];
body_1=[1 4 5 6 8 9 15];
head_2=[7 9 13];
body_2=[5 7 8 9 13 20 30];
head_3=[20 30];
body_3=[4 5 8 11 19 20 30 40 50 100];
A vector head is a subset of vector body. Now I would like to have a collection of all the head vectors, but if a vector head_x is fully in vector body_y, then take head_y instead. If vector head_x is partially in vector body_y, then take head_y instead plus the other elements of head_x. So in my example, the collection would be:
head_final=[7 13 1 6];
In reality I can have several head and body vectors. Any hint will be apprecaitted!

  0 Comments

Sign in to comment.

Accepted Answer

the cyclist
the cyclist on 28 Aug 2020
Edited: the cyclist on 28 Aug 2020
I suggest you read this post about why dynamically named variables are a bad idea. Instead, you'd be better off storing your vectors in cell arrays, as in my code below.
% Define the inputs
head = {[1 6], [7 9 13], [20 30]};
body = {[1 4 5 6 8 9 15], [5 7 8 9 13 20 30], [4 5 8 11 19 20 30 40 50 100]};
% Count of number of inputs
N = numel(head);
% Initialize the vector that holds the head elements that do not appear in other bodies
head_final_cell = cell(1,N);
% Loop over each head
for ii = 1:N
% Define an index that is 1:N, except for the current loop value
other_bodies_index = setxor(1:N,ii);
% Find index to head elements that are *not* in any other body, besides its own
head_not_in_other_body = not(ismember(head{ii},[body{other_bodies_index}]));
% For each head, fill the new cell array with the elements that do notappear in other bodies
head_final_cell{ii} = head{ii}(head_not_in_other_body);
end
% Concatenate all the individual head elements into one vector
head_final = [head_final_cell{:}];
Note that a lot of this code could be compressed into fewer lines, but I separated each step so that I could comment it, and hopefully help you understand what is going on.

  3 Comments

Rub Ron
Rub Ron on 28 Aug 2020
Thank you. Does it makes sense that for this case the output should be: [1 6]?
head = {[1 6], [1 6]};
body = {[1 4 5 6 ], [1 6 7 8 9 13 20 30]};
the cyclist
the cyclist on 28 Aug 2020
Not by my understanding of your rules. I would expect head_final to be empty.
head{1} is [1 6], both elements of which appear in the body{2}.
head{2} is also [1 6], both elements of which appear in body{1}.
So I would not include any head elements. Is that wrong? If so, then please explain the reasoning.
the cyclist
the cyclist on 28 Aug 2020
Regarding your question about vector orientation ...
There are probably a few different ways to handle that, but I think yours should work, yes.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by