How to create a matrix from an equation in Matlab?

249 Views Asked by At

Let A = $(a_{ij})$ be the matrix with entries

$a_{ij} = i^2+j^2$

A is a $N\times N$ matrix

How can I construct a matrix from this equation?

4

There are 4 best solutions below

0
On
s = 1:n;
s2 = s .^ 2;
g = repmat(s2, n, 1);
a = g + g'; 

That, or something very like it, should work. Yep. I tried it. Works fine. Even more matlab-y (although personally I'd avoid this kind of thing):

s = (1:n) .^ 2;
[x,y] = meshgrid(s,s); 
a = x + y;
0
On

I will address the slightly more general situation where $A\in\mathbb{R}^{M\times N}$, and you can just make $M=N$ if you would like.

[iImg,jImg] = meshgrid( 1:N, 1:M );
A = iImg .* iImg + jImg .* jImg;

Or, for more efficiency,

[iSqImg,jSqImg] = meshgrid( (1:N).^2, (1:M).^2 );
A = iSqImg + jSqImg;
4
On
for i = 1:N

    for j = 1:N

      A(i,j) = i^2 + j^2

    end

end
1
On

A simple code with a good performance and without for is:

N = 10; 
range = 1:N;
MI = repmat(range.', 1, N);
MJ = repmat(range, N, 1);
A = MI.^2 + MJ.^2;