Matlab从数组中删除特定元素

时间:2016-07-31 16:06:29

标签: arrays matlab loops vector

我有例如a=[1 2 3 4 5 6 7 8 9 10];,我必须删除3中的每个以下2个数字。
最后它应该是a=[1 4 7 10];
如何在没有for循环的情况下做到这一点。

并且如果有一种方法可以保证最终生成的数组将具有确切数量的条目,就像这里它应该是a,最后有4个条目。

但是例如我们有b=[1 2 3 4 5 6 7 8 9 ];并且如果我想确保最后我在rest数组中仍有4个条目,那么b不能等于[1 4 7]因为我肯定需要4个条目。

3 个答案:

答案 0 :(得分:2)

您可以使用索引:

A = 1:10;
B = A(1:3:end)
B =
    [1 4 7 10]

或者,如果你真的想删除元素:

A = 1:10;
A(2:3:end) = [];
A(3:3:end) = [];

关于长度检查的第二个问题,我们不清楚你在问什么。 if比较是否足够?

if numel(A) ~= 4

    % ... Handle unexpected values here

end

最佳,

答案 1 :(得分:0)

正如您在问题和评论中提到的那样,最后需要4个元素,如果元素小于4,那么您希望包含b的最后一个元素,以下内容应该有效: -

b=[1 2 3 4 5 6 7 8 9] 

b_req=b(1:3:end);
temp=length(b_req);
if temp<4  b_req(end+1:4)=b(end-3+temp:end);    % for including the elements of b so that total elements are 4 at the end
elseif temp>4 b_req=b_req(1:4);                 % for removing the extra elements
end
b_req

<强>输出: -

b = 
     1     2     3     4     5     6     7     8     9

b_req =
     1     4     7     9


和 如果改为b=[1 2 3 4 5 6 7 8 9 10];,则相同的代码会提供您所需的内容,即b_req = [1 4 7 10]

答案 2 :(得分:0)

这段代码不言自明:

a = 1:15; % some vector
% returns every third element after the first one:
third_elemets = a(1:3:end);
% returns the missing elements for the vector to be in size 4 from the end of a
last_elements = a(end-3+length(third_elemets):end);
% take maximum 4 elements from a
logic_ind = true(min(4,length(third_elemets)),1);
% and concatanate them with last_elements (if there are any)
a = [third_elemets(logic_ind) last_elements]

并假设只要少于4个元素,你只需要拿最后一个元素 - 它应该始终有效。

相关问题