Re: Vectorizing using arrayfun or feval?
- From: Doug Schwarz <see@xxxxxxxxxxxxxxxxxxx>
- Date: Fri, 07 Sep 2007 21:05:27 GMT
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.
.
- References:
- Vectorizing using arrayfun or feval?
- From: Lee
- Vectorizing using arrayfun or feval?
- Prev by Date: Re: right-hand text limit color
- Next by Date: Re: How to force plot command not to change predefined properties?
- Previous by thread: Re: Vectorizing using arrayfun or feval?
- Next by thread: Global Variables
- Index(es):
Relevant Pages
|
Loading