필터 지우기
필터 지우기

setdiff for two matrices

조회 수: 6 (최근 30일)
Mahmoud Zeydabadinezhad
Mahmoud Zeydabadinezhad 2016년 3월 18일
댓글: Shuhao Cao 2020년 5월 7일
Hi,
I have two large matrices with the same number of rows but a different number of columns. Let's say A is the larger matrix and B is the smaller one.
Values in each row of the matrix B are a subset of the values of the corresponding row in A. The goal is to have another matrix C which in each row contains the values from the corresponding row of A which are not in corresponding row of B. In other words, I want to use the setdiff(A,B) command, but it should act row by row. Any idea how can I do this without looping?
Thank you!

답변 (2개)

Guillaume
Guillaume 2016년 3월 18일
편집: Guillaume 2016년 3월 18일
I'm afraid there's no other way than looping over the rows either explicitly with a for loop, or with cellfun:
cell2mat(cellfun(@setdiff, num2cell(A, 2), num2cell(B, 2), 'UniformOutput', false))
Note that the above assumes that setdiff returns the same number of elements for each row. Otherwise, you'll have to get rid of the cell2mat call and keep the result as a cell array.
Also, note that an explicit loop may be faster as you wouldn't have to split the inputs into cell arrays of rows.
  댓글 수: 1
Mahmoud Zeydabadinezhad
Mahmoud Zeydabadinezhad 2016년 3월 18일
That's unfortunate as looping over for millions of times takes absolute ages to complete.

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


Fangjun Jiang
Fangjun Jiang 2016년 3월 18일
setdiff(a,b,'rows') ??
  댓글 수: 4
Fangjun Jiang
Fangjun Jiang 2018년 4월 24일
just use setdiff(A(k,:), B(k,:)) and loops through all rows. What is the point to struggle to avoid a loop?
Shuhao Cao
Shuhao Cao 2020년 5월 7일
Because loop is slow for large matrices (especially the sparse matrices).

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by