Initialize index-based MATLAB matrix

I am trying to create a matrix M satisfying:

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

for some f. I can do elementary initialization, say M = zeros(m,n) , then a loop. 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 best way to work with MATLAB. Any clues?

+4
source share
1 answer

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() if it takes matrix arguments and does stepwise math. For example: f = @(i,j) (i+j)/2 or for multiplication: f = @(i,j) i.*j The matrix Ai has the same elements for each row, the matrix Aj has the same elements for each column . The repmat() function repeats a matrix (or vector) into a large matrix.

I also edited above to abstract the vectors xi and xj - you have them as vectors 1:m and 1:n , but they can be arbitrary numeric vectors (for example, [1 2 7.0 pi 1:0.1:20] )

+3
source

All Articles