Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

e.g.

0 2 3
2 0 6
3 6 0

So far I've figured out that I can access the non-diagonal elements with this index matrix

idx = 1 - eye(3)

but I haven't figured out how to incorporate the indices of the matrix cells into the computation.

like image 654
bgoosman Avatar asked Mar 06 '14 22:03

bgoosman


People also ask

How do you select an element in a matrix in MATLAB?

The most common way is to explicitly specify the indices of the elements. For example, to access a single element of a matrix, specify the row number followed by the column number of the element. e is the element in the 3,2 position (third row, second column) of A .

How do you specify an element in MATLAB?

To refer to multiple elements of an array, use the colon ':' operator, which allows you to specify a range of elements using the form 'start:end'. The colon alone, without start or end values, specifies all the elements in that dimension.

How do you reference an element in a matrix?

Each element of a matrix is often denoted by a variable with two subscripts. For example, a2,1 represents the element at the second row and first column of the matrix.

How do you add a value to a matrix in MATLAB?

You can add one or more elements to a matrix by placing them outside of the existing row and column index boundaries. MATLAB automatically pads the matrix with zeros to keep it rectangular. For example, create a 2-by-3 matrix and add an additional row and column to it by inserting an element in the (3,4) position.


2 Answers

I'm considering the general case (matrix not necessarily square). Let

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

There are quite a few approaches:

  1. Using ndgrid:

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

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

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

    result = (1:m).'*(1:n).*~eye(m,n);
    
like image 176
Luis Mendo Avatar answered Oct 24 '22 14:10

Luis Mendo


How about

N=3;  %size of matrix
A=[1:N]'*[1:N]-diag([1:N].^2)
like image 25
Joe Serrano Avatar answered Oct 24 '22 15:10

Joe Serrano