help breaking nested for loop?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I'm trying to create a function that will remove the values from a list called list1 if they are found in list_ind, and if any list_ind value is greater than length(list1), the loop has to stop and print "error". Here's my code:
function [g] = multi_remove(list1,list_ind)
j=1;
for y= list_ind
if list_ind> length(list1)
disp('error')
break
end
for i= 1:length(list1)
if i~=list_ind
g(j)=list1(i);
j=j+1;
end
end
end
So far I can get it to remove the values of list1 found in list_ind but I still have no clue how to terminate the loop if list_ind> length(list1)
0 commentaires
Réponses (2)
Stephen23
le 7 Fév 2018
Modifié(e) : Stephen23
le 7 Fév 2018
break should work: it will exit the for loop when it is executed, and MATLAB will continue with the rest of the function. If you want to leave the function immediately at that point then replace break with return.
Note that repeatedly resizing g will be inefficient, as MATLAB has to move it in memory each time: you could preallocate the output array, but actually some basic MATLAB functions and indexing allow you to do the same much more efficiently, e.g. setdiff:
function out = multi_remove(inp,idx)
out = inp(setdiff(1:numel(inp),idx));
end
will do basically everything that your code does, and is easy to check:
>> inp = 1:9;
>> idx = [3:5,7,99];
>> inp(setdiff(1:numel(inp),idx))
ans =
1 2 6 8 9
You can easily add detection for any conditions that you like, e.g. if any idx value is greater than the number of elements of inp:
if any(idx>numel(inp))
return / error / do whatever
end
0 commentaires
Jan
le 7 Fév 2018
if i~=list_ind
This does not do, what you want. You mean:
if all(list(i) ~= list_ind)
or
if ~any(list(i) == list_ind)
You do not want:
if list_ind> length(list1)
but
if y > length(list1)
Or you can check this before the loop:
if any(list_ind > length(list1))
error('Failed');
end
0 commentaires
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!