Follow the method on the link provided below.
Remove a number and its duplicates, not just the repeated values i.e. the way the unique function operates
6 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
更多回答(1 个)
Thomas Satterly
2019-11-13
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 NaNs 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!