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.
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 .
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.
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.
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.
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:
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);
How about
N=3; %size of matrix
A=[1:N]'*[1:N]-diag([1:N].^2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With