Initialize MATLAB matrix based on indices
I'm trying to create a matrix M satisfying:
M(i,j) = f(i,j)
for some f. I can do elementwise initialization through s开发者_如何转开发ay 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!
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]
)
精彩评论