Borrar filtros
Borrar filtros

i have a vector in lenght 5, i need to check if a sum of 2 or more elements in the vector is equal to another element at the same vector how to do that?

54 visualizaciones (últimos 30 días)
i have a vector in lenght 5, i need to check if a sum of 2 or more elements in the vector is equal to another element at the same vector how to do that?
i try to do a loop inside a loop but it doesnt works
if someone has an idea it would be helpful.
thank you

Respuesta aceptada

Ayush Aniket
Ayush Aniket el 16 de Jul. de 2024 a las 15:16
Editada: Ayush Aniket el 17 de Jul. de 2024 a las 3:59
Hi Omer,
You can check for the existence of an element which is the sum of two or more elements in the same vector as follows:
  1. Select all combinations of numElements(number of elements) from the vector, where numElements varies from 2 to 5. You can use the nchoosek MATLAB function which returns all the combinations. Refer to the doumentation for the function here: https://www.mathworks.com/help/matlab/ref/nchoosek.html
  2. The next step would be to iterate through the combinations, find the sum and check for the result in the vector. See the code below:
% Iterate over all combinations of 2 or more elements
for numElements = 2:n
combs = nchoosek(1:n, numElements); %Find indices of all combinations of size numElements from the vector
for i = 1:size(combs, 1)
sumComb = sum(vec(combs(i, :)));
if any(vec == sumComb)
result = true;
return;
end
end
end
The result variable returns the answer. The initial value will be false for this variable.
  2 comentarios
omer
omer el 16 de Jul. de 2024 a las 19:54
hi, thanks!
just for understandin what does 'n' means?
combs = nchoosek(1:n, numElements)
Ayush Aniket
Ayush Aniket el 17 de Jul. de 2024 a las 4:17
Hi Omer, the n refres to the length of the original vector vec i.e.
n = length(vec)
For this problem, the value of n will be 5. In the function nchoosek, we construct and pass the vector 1:5 ([1,2,3,4,5], representing the indices of the original vector) as the vector argument. The function then returns the combination of numElements number of elements from this vector.

Iniciar sesión para comentar.

Más respuestas (1)

Voss
Voss el 16 de Jul. de 2024 a las 15:08
v = [10 5 13 15 28];
m = dec2bin(0:2^numel(v)-1)-'0';
m = m(sum(m,2) >= 2,:);
[ism,idx] = ismember(m*v.',v);
idx = idx(ism);
m = logical(m(ism,:));
for ii = 1:numel(idx)
disp(join(compose('%g',v(m(ii,:))),'+') + "=" + v(idx(ii)))
end
13+15=28 10+5=15 10+5+13=28

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by