how can i avoid repetition of number during Comparing Numbers of vector By trail and error method .
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
I want to compare all the numbers in vector in condition that there sum should be in range 39.5 to 40.5. in output i want the element number in table of 3 columns, fisrt column give me element serial number if first element and second cloumn gives serial number of second element and 3rd columns shows the sum of numbers.
when i do so, by the fololowing code;
clear
clc
a=[29.70
10.28
15
31.46
13.17
32.63
33.22
25
29.40
34.98
35.57
36.16
29.67
26.82];
x=1:numel(a);
y=1:numel(a);
N1=0;
N2=0;
CL=0;
for i=x
for k=y
c= a(i)+a(k);
if (c>39.5) & (c<40.5);
if i~=N1 & k~=N2
N1=[N1,i];
N2=[N2,k];
CL=[CL,a(i)+a(k)];
end
else
disp('no');
end
end
end
it gives this result:
T =
Var1 Var2 Var3
____ ____ _____
0 0 0
1 2 39.98
2 1 39.98
3 8 40
5 14 39.99
8 3 40
14 5 39.99
but i want this result:
T =
Var1 Var2 Var3
____ ____ _____
0 0 0
1 2 39.98
3 8 40
5 14 39.99
i dont want that it repeat the numbers of second column again in first column. something like that.
0 comentarios
Respuestas (1)
Harshavardhan
el 30 de Abr. de 2025
Hi @Fahad Anees
The code currently finds all pairs (i, k) such that the sum is in the desired range, including both (i, k) and (k, i), which leads to duplicate pairs (just swapped).
To avoid repeated pairs, only check pairs where k > i. This ensures each unique pair is considered only once.
results = []; % To store [i, k, sum]
for i = 1:numel(a)
for k = i+1:numel(a) % Only k > i
s = a(i) + a(k);
if s > 39.5 && s < 40.5
results = [results; i, k, s];
end
end
end
T = array2table(results, 'VariableNames', {'Var1','Var2','Var3'});
disp(T)
For more information on “array2table”, you can refer to the documentation by typing the following command in a MATLAB command window.
doc array2table
Hope this helps.
0 comentarios
Ver también
Categorías
Más información sobre Numerical Integration and Differentiation en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!