MATLAB Answers

Remove a number and its duplicates, not just the repeated values i.e. the way the unique function operates

1 view (last 30 days)
Vance Blake
Vance Blake on 13 Nov 2019
Edited: Vance Blake on 24 Jan 2020
Hi, I am trying to remove both the number itself and its duplicates from my matrix. For example if A was the matrix (column vector in this case but could be a matrix in the future) shown below, I wish to remove all the 2's and 3's from it, but unique(A); would just remove the second 2 and 3 respectively. I use this matrix as an example but it could be any number that is duplicated any number of times. I would like to remove both the number and its repeats from the matrix (vector). Thanks for all tips and information. Lemme know if any clarification is needed.
A = [2;2;4;3;3;5;6];

  0 Comments

Sign in to comment.

More Answers (1)

Thomas Satterly
Thomas Satterly on 13 Nov 2019
This should lead you along the right track:
% Ex:
% A = [2;2;4;3;3;5;6];
% remove(A, 2) Removes all 2's
% remove(A, 2, 3) Removes all 2's and 3's
function x = remove(x, varargin)
if sum(size(x) > 1) > 1
% Matrix, cannot just "remove" indecies without it being converted
% into an array
for i = 1:numel(varargin)
x(x == varargin{i}) = nan;
end
else
% It's an array, so we can remove indecies and the array will just
% get shorter
for i = 1:numel(varargin)
x(x == varargin{i}) = [];
end
end
end
You can't simply remove data at any index from a matrix and still have a matrix because the matrix dimensions must be preserved. If you do attempt to do this, the matrix will be converted into an array. You can, however, remove entire dimensions from a matrix, e.g. to remove a row from matrix B:
B = rand(3, 5);
B(2, :) = []; % Removes the second row

  1 Comment

Vance Blake
Vance Blake on 13 Nov 2019
Hey thanks for the suggestion but I found a related link that came up when I posted my question that solved my problem. Thanks again tho.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by