delete an element in a cell array in a for loop
2 次查看(过去 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 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!