How to find 3 elements from multiple vectors that meet a given condition 3 element condition?

2 次查看(过去 30 天)
I have several (more than 3) 1xN vectors. I am trying to find a column number i, and 3 vectors X, Y, Z, which satisfy the condition X_i -Y_i = Y_i -Z_i. An example of what I am trying to do is shown below:
W = [1 2 3];
X = [0 2 4];
Y = [1 3 5];
Z = [1 4 9];
%[i, A, B, C] = searchfunction(W,X,Y,Z);
find(W - X == X - Y)
find(W - Y == Y - Z)
find(X - Y == Y - Z)
I would like the search function to find the solutions:
i = 1, for W, Y, Z => because W(1) - Y(1) = Y(1) - Z(1)
i = 2, for W, Y, Z => because W(2) - Y(2) = Y(2) - Z(2)
i = 2, for X, Y, Z => because X(2) - Y(2) = Y(2) - Z(2)
i =3, for W, X, Y => because W(3) - X(3) = X(3) - Y(3)
My code above does this, but if I have N vectors I have to write N-1 find statements to get all the answers. I would like to have a more compact and efficient way of finding the solutions.

回答(1 个)

Paras Gupta
Paras Gupta 2022-6-8
编辑:Paras Gupta 2022-6-8
Hi,
It is my understanding that you are able to determine the solution using the “find” function but require a way to avoid manually writing down the code for iterating over the possible combination of vectors.
The following code illustrates one possible way to efficiently achieve the same.
W = [1 2 3]; % Vector 1
X = [0 2 4]; % Vector 2
Y = [1 3 5]; % Vector 3
Z = [1 4 9]; % Vector 4
%% Concatenate all vectors
concatTemp = [W;X;Y;Z];
n = size(concatTemp);
%% Find all combinations of 3 rows in the concatenated matrix
c = nchoosek(1:n,3);
%% For each combination, find the solution
for k=1:size(c)
vectors = c(k, :);
A = concatTemp(vectors(1), :);
B = concatTemp(vectors(2), :);
C = concatTemp(vectors(3), :);
i = find( A - B == B - C);
if isempty(i)
i = "No Solution";
end
disp(['For vectors, ', num2str(vectors),', the solution, i = ', num2str(i)])
end
For vectors, 1 2 3, the solution, i = 3 For vectors, 1 2 4, the solution, i = No Solution For vectors, 1 3 4, the solution, i = 1 2 For vectors, 2 3 4, the solution, i = 2
Please refer to nchoosek and Colon documentation for more information on computing the combinations and indexing a matrix respectively.
Hope it helps!

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by