setdiff for two matrices

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 个评论

That's unfortunate as looping over for millions of times takes absolute ages to complete.

请先登录,再进行评论。

Fangjun Jiang
Fangjun Jiang 2016-3-18

0 个投票

setdiff(a,b,'rows') ??

4 个评论

No, that's not what the 'rows' option does. It treats each row as a single entity and return the rows that are not found in the second matrix. Even if it didn't error, this is not what is asked. It returns an error in any case, since with 'rows' the rows must have the same number of columns.
Hi, I am curious to know whether you were able to solve the problem eventually because I am stuck with similar problem myself and am wondering if I could benefit from your experience.
just use setdiff(A(k,:), B(k,:)) and loops through all rows. What is the point to struggle to avoid a loop?
Because loop is slow for large matrices (especially the sparse matrices).

请先登录,再进行评论。

类别

帮助中心File 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