MATLAB Answers

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

조회 수: 1(최근 30일)
Vance Blake
Vance Blake 2019년 11월 13일
편집: Vance Blake 2020년 1월 24일
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];

추가 답변(1개)

Thomas Satterly
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;
% 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}) = [];
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
Vance Blake
Vance Blake 2019년 11월 13일
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.

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

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

Start Hunting!

Translated by