我想在while循环中编写一个代码,该代码根据条件删除向量的元素,同时在每次迭代中保留这些被删除元素的索引?
b=[2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 ];
y = b;
while length(y)>4
idx=find(y(1:3:end));
y=y(1:3:end);
disp(y);
disp(idx);
end
答案 0 :(得分:1)
以下是记录每次迭代中已删除元素的索引的代码:
clc;
clear;
b = [2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1];
% vector y indicating the indices of elements of b
y = 1:length(b);
% cell array which records the index of elements to be removed in each iteration
idxRemoval = cell();
while true
if length(y) <= 4
break;
end
idx = y(1:3:end);
% save the indices of removed elements of b
idxRemoval{end+1} = setdiff(y,idx);
% update y such that removed elements are excluded from the next iteration
y = setdiff(y,idx);
end
我在Octave中运行了代码,但是我相信它也可以在Matlab中运行。输出idxRemoval
如下:
>> idxRemoval
idxRemoval =
{
[1,1] =
2 3 5 6 8 9 11 12 14 15 17 18 20
[1,2] =
3 5 8 9 12 14 17 18
[1,3] =
5 8 12 14 18
[1,4] =
8 12 18
}
此外,如果要查看在每次迭代中如何删除b
中的元素,可以使用以下代码:
bRemoval = cellfun(@(k) b(k), idxRemoval, "UniformOutput", false);
这样您将看到
bRemoval =
{
[1,1] =
3 4 6 7 9 0 2 3 5 6 8 9 1
[1,2] =
4 6 9 0 3 5 8 9
[1,3] =
6 9 3 5 9
[1,4] =
9 3 9
}