Set element i, j to matrix in i * j in matlab

I want to generate a matrix in which the element i, j is equal to i * j, where i! = J.

eg.

0 2 3 2 0 6 3 6 0 

So far, I have figured out that I can access off-diagonal elements using this index matrix

 idx = 1 - eye(3) 

but I did not understand how to include the indexes of the matrix cells in the calculation.

+6
source share
4 answers

I consider the general case (the matrix is ​​not necessarily square). Let be

 m = 4; %// number of rows n = 3; %// number of columns 

There are quite a few approaches:

  • Using ndgrid :

     [ii jj] = ndgrid(1:m,1:n); result = (ii.*jj).*(ii~=jj); 
  • Using bsxfun :

     result = bsxfun(@times, (1:m).',1:n) .* bsxfun(@ne, (1:m).',1:n); 
  • Using repmat and cumsum :

     result = cumsum(repmat(1:n,m,1)); result(1:m+1:m^2) = 0; 
  • Using matrix multiplication (added by @ GastónBengolea):

     result = (1:m).'*(1:n).*~eye(m,n); 
+9
source

What about

 N=3; %size of matrix A=[1:N]'*[1:N]-diag([1:N].^2) 
+7
source

Another trick is to use the kron function:

 >> m = 4; >> n = 3; >> a = kron((1:m)', 1:n); >> a(eye(m, n, 'logical')) = 0 a = 0 2 3 2 0 6 3 6 0 4 8 12 
+4
source
 for i=1:3 for j=1:3 if i==j A(i,j)=0; else A(i,j)=i*j; end end end 
+3
source

All Articles