tags:

views:

47

answers:

1

I'm trying to create a matrix M satisfying:

M(i,j) = f(i,j)

for some f. I can do elementwise initialization through say M = zeros(m,n) then looping. For example (in Octave):

M = zeros(m,n)
for i = 1 : m
  for j = 1 : n
    m(i, j) = (i+j)/2;
  endfor
endfor

But AFAIK loops are not the optimal way to go with MATLAB. Any hints?

+2  A: 

Sure!

 xi = 1:m;
 xj = 1:n;
 Ai = repmat(xi',1,length(xj));
 Aj = repmat(xj,length(xi),1);
 M = f(Ai,Aj);

You can do this with any f() so long as it takes matrix arguments and does element-by-element math. For example: f = @(i,j) (i+j)/2 or for multiplication: f = @(i,j) i.*j The Ai matrix has identical elements for each row, the Aj matrix has identical elements for each column. The repmat() function repeats a matrix (or vector) into a larger matrix.

I also edited the above to abstract out vectors xi and xj -- you have them as 1:m and 1:n vectors but they can be arbitrary numerical vectors (e.g. [1 2 7.0 pi 1:0.1:20])

Jason S
Thanks! I guess that's similar to what `x` and `y` are in, say, `[x,y] = meshgrid(1:1:m+1)`.
M.S.
If `f` can take more than scalar inputs, then `bsxfun` will do this with less typing!
Oli Charlesworth
@Oli: you should add that as another answer!
Jason S

related questions