help breaking nested for loop?
조회 수: 1 (최근 30일)
이전 댓글 표시
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
답변 (2개)
Stephen23
2018년 2월 7일
편집: Stephen23
2018년 2월 7일
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
Jan
2018년 2월 7일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!