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

1 次查看(过去 30 天)
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...

采纳的回答

Dyuman Joshi
Dyuman Joshi 2023-1-18
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 个评论
Dyuman Joshi
Dyuman Joshi 2023-1-19
编辑:Dyuman Joshi 2023-1-19
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by