MATLAB Answers

Extract values common to 5 columns

10 views (last 30 days)
Curious Mind
Curious Mind on 24 Jan 2020
Answered: Star Strider on 24 Jan 2020
Hi, I have a matrix A with 5 columns (1 to 5). I want to compare columns 1 through 5 and then extract values common to all 5 columns. Put the extracted values (common to all 5 columns) into a separate matrix called Match. Thank you!

  4 Comments

Show 1 older comment
Curious Mind
Curious Mind on 24 Jan 2020
I have a code that solves this task if there are only 2 columns under consideration.
data = randi(3,12,4); NewMatch = data(:,2) == data(:,4); Print = data(NewMatch,:)
I want to extract common values in all 5 columns this time. The above code compares just 2 columns. Any thoughts?
Star Strider
Star Strider on 24 Jan 2020
Is this homework? If so we can only give hints.
If it is not homework, I will post my general solution.
Curious Mind
Curious Mind on 24 Jan 2020
Not at all. Not a homework.

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 24 Jan 2020
Since it is not homework, see if this does what you want:
A = randi(9,20,5); % Create Matrix (Integers For Simplicity)
[Au,ia,ic] = unique(A); % Unique Elements (Use ‘uniquetol’ For Non-Integers)
[~,c] = ind2sub(size(A), (1:numel(A)).'); % Create Vector Of Column Indices
Tally = accumarray(ic,c,[],@(x){Au(x)}); % Accumulate By Column
ColsWithAu = cellfun(@(x)nnz(ismember(Au,x)), Tally); % Return Columns With Specific Elements
Common = Au(ColsWithAu==5) % If Element Appears In Every Column, It Is Common To All Columns
It worked for my test matrix.
If your rmatrix has floating-point elements, use uniquetol instead of unique. You will need to choose the appropriate tolerance value.

  0 Comments

Sign in to comment.

More Answers (1)

James Tursa
James Tursa on 24 Jan 2020
Hint: Look at the result of diff(A,[],2). If all the values in a row are equal, what would you expect to be in the result of this diff calculation? Can you devise a test base on this result to see if every value in a row is the same?

  0 Comments

Sign in to comment.

Sign in to answer this question.

Products


Release

R2019b

Translated by