Clear Filters
Clear Filters

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

1 view (last 30 days)
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...

Accepted Answer

Dyuman Joshi
Dyuman Joshi on 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 Comments
Brandon Tsang
Brandon Tsang on 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 on 19 Jan 2023
Edited: Dyuman Joshi on 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

Sign in to comment.

More Answers (0)

Categories

Find more on Resizing and Reshaping Matrices in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!