Re: Vectorizing using arrayfun or feval?



Lee wrote:
M1 is (N by K) and M2 is (M by K). I would like the results
of subtracting each row of M2 from each row of M1, which
amounts to doing M1-repmat(M2(1,:),N,1),
M1-repmat(M2(:,2),N,1), etc.

In Mathematica, this can be done in a single statement
Map[(M1-#)&, M2] which returns M matrices of size N by K as the result. (Note: the # is a variable in the anonymous
function the does the subtraction for each row in M2; and
mathematica automatically vectorizes subtraction of a vector
from each row of a matrix).

I've tried using feval() and arrayfun() to do something
similar in Matlab, avoiding looping (and avoiding repmat, if
possible), but I cannot find a way to this simply. Neither
feval nor arrayfun seem to take a matrix as the input
argument of the anonymous function and map the function to
cols or rows of the matrix.

Lee,

MATLAB seems to be a bit more explicit in this case, but I think the closest equivalent to Map[(M1-#)&, M2] would be

c = cellfun(@(x)bsxfun(@minus,M1,x),num2cell(M2,2),'UniformOutput',false);

Where the result is a cell array containing the M matrices. However, I would be much more likely to write

c = cell(M,1);
for i = 1:M
c{i} = bsxfun(@minus,M1,M2(i,:));
end

as it is easier to understand, faster and requires fewer keystrokes to enter! Don't get hung up on trying to do everything in one line.

--
Doug Schwarz
dmschwarz&ieee,org
Make obvious changes to get real email address.
.



Relevant Pages

  • Vectorizing using arrayfun or feval?
    ... I am former Mathematica user (where nearly all functions ... vectorize certain routine operations in Matlab, ... mathematica automatically vectorizes subtraction of a vector ...
    (comp.soft-sys.matlab)
  • Re: background subtraction in x-rays
    ... i am working on MATLAB and am restricted to MATLAB as ... though background subtraction seems a very common topic ... image as my operating image which is a digital x-ray. ...
    (sci.image.processing)
  • Re: Background Subtraction: Coverting from Java to Matlab code
    ... background so the thresholding methods that I am using can catch all ... do not know how to correctly covert the Java code to Matlab code. ... Now if you had x rays, you could do subtraction as ... then fit some smooth function to it. ...
    (comp.soft-sys.matlab)
  • Re: floating point calculation bug?
    ... Kyongje Sung wrote: ... I'm having a problem in doing simple addition and subtraction with ... floating numbers. ... It looks like MATLAB has a problem in dealing with decimal places. ...
    (comp.soft-sys.matlab)
  • floating point calculation bug?
    ... I'm having a problem in doing simple addition and subtraction with ... floating numbers. ... It looks like MATLAB has a problem in dealing with decimal places. ... I'm using Mac OS X (tiger) and MATLAB 7.1. ...
    (comp.soft-sys.matlab)

Loading