0

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?

nonuser
  • 90,026

4 Answers4

2
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;
John Hughes
  • 93,729
0

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;
NicNic8
  • 6,951
0
for i = 1:N

    for j = 1:N

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

    end

end
Mason
  • 631
  • 4
  • 11
  • For $N = 1000$, this is about twenty times slower than my second solution, and about 30 times slower than my first. There are idioms in programming languages for a reason. – John Hughes Jul 06 '19 at 00:15
  • @JohnHughes yes you are correct, but for completeness I included this implementation since you already listed the other way. For small enough N, this is completely feasible and easier to understand. – Mason Jul 06 '19 at 00:35
  • I can't agree. One might equally well argue that "Pleased to meet you" is easier to understand than "enchanté de faire votre connaissance," but that's only if you're speaking English. Back in the days of APL, you could always tell a FORTRAN programmer's APL code, because it was almost impossible to read, having been literally translated from the FORTRAN, and therefore full of loops and tests and go-tos, rather than using the vector/matrix/tensor operations that were built into APL, often as single characters. My TAs sometimes joke about "Jacket," i.e., Java code written in Racket. It's awful. – John Hughes Jul 06 '19 at 17:26
  • @JohnHughes noted, thanks – Mason Jul 06 '19 at 19:05
0

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;
OmG
  • 3,138