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)
Show older comments
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...
0 Comments
Accepted Answer
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
2 Comments
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
More Answers (0)
See Also
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!