MATLAB Answers

# Extract values common to 5 columns

조회 수: 11(최근 30일)
Curious Mind 2020년 1월 24일
답변: Star Strider 2020년 1월 24일
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표시숨기기 이전 댓글 수: 3
Curious Mind 2020년 1월 24일
Not at all. Not a homework.

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

### 채택된 답변

Star Strider 2020년 1월 24일
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.

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

### 추가 답변(1개)

James Tursa 2020년 1월 24일
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?

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

R2019b

### Community Treasure Hunt

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

Start Hunting!