Add particular elements of array
Afficher commentaires plus anciens
Let's say that k is a vector and
k = [1 1 1 1 4 1 1];
k could be anything I just assumed [1 1 1 1 4 1 1]. Let's say there is a variable
limiter = 3;
I want to add elements of k that are less than or equal to the variable 'limiter' and put it in a new vector, let's say k_new. For example, k(1),k(2),k(3),k(4) <= limiter, add them and put it in k_new resulting
k_new = [4];
Now k(5) is greater than limiter, it should be ignored and should be stored in k_new as it is, resulting
k_new = [4 4];
the final desired vector is
k_new = [4 4 2]
I worte a program using two while loops and somehow the loop keeps running. I want to do this using a single while loop if possible and I need help in doing that. Below is my code
limiter = 3;
k = [1 1 1 1 4 1 1];
run1 = true;
while (run1)
ii = 1;
jj = 1;
run2 = true;
while (run2)
if (k(ii) < limiter)
k_new(jj) = k(ii)+k(ii+1)
ii = ii + 2; % increment of 2 because we need
% to check k(ii+2) as k(ii) and k(ii+1) have been checked
else
k_new(jj) = k(ii)
ii = ii + 1;
end
jj = jj + 1;
if (ii == length(k))
k_new(jj) = k(ii)
break
end
if (ii > length(k))
run2 = false;
end
end
k = k_new
clear k_new
if (find(k==min(k),1,'last') == length(3)) % Stop the outer while loop
run1 = false;
break
end
end
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!