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

3 views (last 30 days)
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.

Answers (1)

Paras Gupta
Paras Gupta on 8 Jun 2022
Edited: Paras Gupta on 8 Jun 2022
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!

Tags

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!