loop for removing highest value until specific value is reached

1 vue (au cours des 30 derniers jours)
형준 이
형준 이 le 18 Juil 2022
Commenté : 형준 이 le 19 Juil 2022
for exmaple,
for 10x10 matrix A
i want to make loop which removes highest element until sum of A is less than 20
and i want to know each removed element's position
i think 'while-loop' is needed
( I only know finding the first highest value using 'for-loop')

Réponse acceptée

Adam Danz
Adam Danz le 18 Juil 2022
A = randi(13,10);
while sum(A,'all','omitnan')>20
[~,idx] = max(A(:),[],'omitnan');
A(idx) = NaN;
end
isRemoved = isnan(A)
isRemoved = 10×10 logical array
1 1 0 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 0 1 1 1 0 1 1 1 1 1 0 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0 1 1 1
sum(A,'all','omitnan')
ans = 19

Plus de réponses (1)

David Hill
David Hill le 18 Juil 2022
[b,idx]=sort(A(:));
IDX=idx(cumsum(b)>=20);%linear index of each of the removed element's position

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by