delete an element in a cell array in a for loop
조회 수: 1 (최근 30일)
이전 댓글 표시
hello; l have a set called stated_n{i} where i varies from 1 to n (let n=5) for exemple
stated_n{1} = {3,7,8,9,14,99}
stated_n{2} = {14,8,19,104,98}
stated_n{3} = {67,7,8,9,14,11}
stated_n{4} = {41,76,8,18,14,56}
stated_n{5} = {65,13,16,9,8,103}
l want for exemple to delete a value k (let k= 8) how to do that to remove 8 from each stated_n (1:5)
for i=1:N
if ismember(k,stated_n{i})
%remove k from stated_n{i}
% update stated_n{i} and display it
end
end
댓글 수: 3
the cyclist
2015년 3월 12일
OK, but be aware that you keep using curly brackets "{}", which is how cell arrays are specified.
I will modify my code below in a way that I hope will make it work.
채택된 답변
추가 답변 (4개)
Sara Hafeez
2015년 3월 12일
The method will be first find the index of the number 8 in a loop in every cell array and then use the following stated_n{index}=[] this will remove the value of 8 and yes find the value ofn8 by comparing or by a conditional statement.
the cyclist
2015년 3월 12일
편집: the cyclist
2015년 3월 12일
If you really have a cell array of cell arrays, then I think this will work:
output = cellfun(@(x)num2cell(setdiff([x{:}],8)),stated_n,'UniformOutput',false)
EDIT BASED ON COMMENTS ABOVE
cellfun(@(x)setdiff(x,8),stated_n,'UniformOutput',false)
댓글 수: 4
the cyclist
2015년 3월 12일
편집: the cyclist
2015년 3월 12일
My code does work.
Use this version:
cellfun(@(x)setdiff(x,8),stated_n,'UniformOutput',false)
It does not need to be inside the for loop:
output = cellfun(@(x)(setdiff(x,F)),neighbour_n,'UniformOutput',false);
for i=1:N
display(['Display new neighbour of ', num2str(i), ' are: ', num2str(neighbour_n{i})]);
end
I defined a new variable called output, but you are just displaying your old variable, neighbour, so you did not see the deletions.
The new variable has what you want. Maybe you want to do
neighbour_n = cellfun(@(x)(setdiff(x,F)),neighbour_n,'UniformOutput',false);
for i=1:N
display(['Display new neighbour of ', num2str(i), ' are: ', num2str(neighbour_n{i})]);
end
Sara Hafeez
2015년 3월 12일
OK don't have a PC here writing this in random on mobile just check if it runs properly For i=1:5% because there are 5 parts
For j=1:6
If stated{i,j}=8 Then set this to an empty array and the end the loop try this hope it works.
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!