How do I prevent duplicate indexes in an array from subtracting to each other when it satisfies the condition the 1st time?

2 vues (au cours des 30 derniers jours)
matA = [21 36 172 246 259 274 303 311 316 322 340 375 377 378 382 396 483 508]
matB = [39 116 198 203 309 314 364 421]
A = 1:1:numel(matA); B=1:1:numel(matB)
for i = A
for j = B
if matA(i) > matB(j)
matA(i)-matB(j)
end
end
end
%order: 172-39=133, 172-116=56, 246-116=130, 246-39=207,246-198=48
%What I want outputted from: 133, 56, 48 (prevent 130 and 207 from happening)
Matlab output:
ans = 133
ans = 56
ans = 207
ans = 130
ans = 48
ans = 43
etc...

Réponse acceptée

Dyuman Joshi
Dyuman Joshi le 18 Jan 2023
matA = [21 36 172 246 259 274 303 311 316 322 340 375 377 378 382 396 483 508];
matB = [39 116 198 203 309 314 364 421];
idx=[];
for i = 1:numel(matA)
for j = setdiff(1:numel(matB),idx)
if matA(i) > matB(j)
matA(i)-matB(j)
idx=[idx j];
end
end
end
ans = 133
ans = 56
ans = 48
ans = 43
ans = 2
ans = 2
ans = 11
ans = 62
  2 commentaires
Brandon Tsang
Brandon Tsang le 19 Jan 2023
Thanks Dyuman! How would you go about outputting only the highest value out of all the generated for loop outputs?
Dyuman Joshi
Dyuman Joshi le 19 Jan 2023
Modifié(e) : Dyuman Joshi le 19 Jan 2023
You can use a value and update it as per the condition -
matA = [21 36 172 246 259 274 303 311 316 322 340 375 377 378 382 396 483 508];
matB = [39 116 198 203 309 314 364 421];
idx=[];
y=-Inf;
for id = 1:numel(matA)
for jd = setdiff(1:numel(matB),idx)
if matA(id) > matB(jd)
y=max(y,matA(id)-matB(jd));
idx=[idx jd];
end
end
end
y
y = 133

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Resizing and Reshaping Matrices dans Help Center et File Exchange

Produits


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by