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?
Sure!
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)/2or for multiplication:f = @(i,j) i.*jThe Ai matrix has identical elements for each row, the Aj matrix has identical elements for each column. Therepmat()function repeats a matrix (or vector) into a larger matrix.I also edited the above to abstract out vectors
xiandxj— you have them as1:mand1:nvectors but they can be arbitrary numerical vectors (e.g.[1 2 7.0 pi 1:0.1:20])