How to remove a particular value (index) from an array? And also how to add a particular variable to an existing array?

8 views (last 30 days)
hs(n) = {1,2,3,4} if i want to remove '3' from hs(n). What should i do? if i want to add '5' to hs(n). What should i do? Please use some variables to answer this ... Thanks in advance :)

Accepted Answer

KSSV
KSSV on 17 Feb 2017
% if cell
hc = {1,2,3,4} ;
hc{3} = 5 ;
% if matrix
hm = [1 2 3 4] ;
hm(3) = 5 ;
  3 Comments
KSSV
KSSV on 17 Feb 2017
Let i = 3 be the index you want to remove:
If cell:
hc = {1,2,3,4} ;
hc{3} = [] ;
hc(~cellfun('isempty',hc))
If matrix;
hc = [1 2 3 4] ;
hc(3) = []

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 17 Feb 2017
Edited: Walter Roberson on 17 Feb 2017
mask = ismember(hs(n), 'a');
hs{n}(mask) = [] ;
Note that the order of arguments for the ismember for this purpose is the opposite of what you might expect.
Also this code expects a cell array of strings, consistent with your use of '3' but not consistent with your initial assignment which had a cell array of numeric values. You used the string form more so I programmed for that.

Categories

Find more on Numeric Types in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!