delete element from vector

5,341 次查看（过去 30 天）
Majid Al-Sirafi 2012-9-24

Hi everyone
how can I delete element from vector .... for example
a=[1,2,3,4,5]
how can I delete 3 from above vector to be
a=[1,2,4,5]
thank you
majid
7 个评论显示 6更早的评论隐藏 6更早的评论
Hamna Ameer 2017-9-29

a(3)=[] how can i directly store this in a new vector say b?

采纳的回答

Daniel Shub 2012-9-24

I can think of three ways that are all slightly different
a=[1,2,3,4,5];
If you want to get rid of all cases where a is exactly equal to 3
b = a(a~=3);
If you want to delete the third element
b = a;
b(3) = [];
or on a single line
b = a([1:2, 4:end]);
Or, as Jan suggests:
a = [2,3,1,5,4]
a(a == 3) = []
6 个评论显示 5更早的评论隐藏 5更早的评论
Rik 2021-3-31
@Anthony Dave Flags are not for personal bookmarks. Please remove your flag.

更多回答（5 个）

Jan 2012-9-24

a = [1,2,3,4,5]
a(3) = []
Or:
a = [2,3,1,5,4]
a(a == 3) = []
These methods are explained exhaustively in the "Getting Started" chapters of the documentation. It is strongly recommended to read them completely. The forum is not though to explain the fundamental basics. Thanks.
3 个评论显示 2更早的评论隐藏 2更早的评论
irvin rynning 2021-12-6
unfortunately some of us prefer to use Matlab to solve problems in a timely manner, and cannot always engage in stackover-flow style plaudits on criticizing one's peers

A = [ 1 2 3 4 5 6 7]
A = 1×7
1 2 3 4 5 6 7
B = [1 3 6]
B = 1×3
1 3 6
C = setdiff(A,B)
C = 1×4
2 4 5 7
2 个评论显示 1更早的评论隐藏 1更早的评论
Emma Fickett 2022-10-29
I've scoured through so many forums trying to remove a vector of values from another vector and setdiff does exactly what I needed, thank you so much!!

Andrei Bobrov 2012-9-24
a = a(abs(a - 3) > eps(100))
1 个评论显示 无隐藏 无
Majid Al-Sirafi 2012-9-24
than you very much

Will Reeves 2022-2-15
really crude, but if you wanted to remove a row defined by and index, rather than a value, you could do something like this:
function out=removeRow(in,index)
% removes a row from an matrix
[~,n]=size(in);
if index>n || index<0
error('index needs to be within the range of the data')
else
if n==1
out=[]; % you've removed the last entry
else
% strip out the required entry
if index==1
out=in(2:end);
elseif index==n
out=in(1:end-1);
else
out=in([1:index-1 index+1:n]);
end
end
end
0 个评论显示 -1更早的评论隐藏 -1更早的评论

Elias Gule 2015-12-1
% Use logical indexing
a = a(a~=3)
2 个评论显示 1更早的评论隐藏 1更早的评论
Ntsakisi Kanyana 2020-3-31
Does it work on strings?

类别

Find more on Matrix Indexing in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by