unique vector with restrictions
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
the cyclist
2020-8-28
编辑:the cyclist
2020-8-28
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 个评论
the cyclist
2020-8-28
编辑:the cyclist
2020-8-28
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
2020-8-28
Regarding your question about vector orientation ...
There are probably a few different ways to handle that, but I think yours should work, yes.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!