Search code examples
matlabloopsmatrixsparse-matrix

Matlab create matrix by iterating the same command several times without for loop


I have a code like this:

A = [sparse(round(rand(4,4)))];
B = [sparse(round(rand(1,4)))];
C = [bsxfun(@minus,A(1,:),B); bsxfun(@minus,A(2,:),B); bsxfun(@minus,A(3,:),B); bsxfun(@minus,A(4,:),B);]

Is is possible to somehow define C this way for a large amount rows (so that I cannot physically print the command this way) WITHOUT a loop (because a loop would take an excessively long time)?


Solution

  • One another options:

    If you prefer to keep a sparse matrix:

    C = A - repmat(B,size(A,1),1); %but slower than the bsxfun version.