

I have a matrix M which is a function of two variables, x and y, and I want to diagonalize it for many pairs of x and y. If I index x as x(u) and y as y(v), then I can write the elements of the matrix as M(i,j,u,v) where i and j index which element of the matrix.
Currently I am constructing and diagonalizing the matrices with for loops: x = linspace(0,1,5);
for u=1:5 for v=1:5
M = [ y(v)*x(u) , x(u) ; x(u) , y(v)^2 ];
[vecs(:,:,u,v),vals
(:,:,u,v)] = eig(M(:,:,u,v));
end end
I've been able to vectorize almost all the rest of my code, and this is the last part. Is there a way to vectorize this? My experience with vectorization is fairly limited, so please let me know if you have any side comments on this  for example, whether vectorization would actually speed it up.
I should add that although my MWE is a 2x2, I would in practice be doing this with a 4x4 matrix, if that is relevant to whether or not vectorizing the diagonalization would actually do much to accelerate my code.


Currently I am constructing and diagonalizing the matrices with for loops:
x = linspace(0,1,5);
for u=1:5 for v=1:5
M = [ y(v)*x(u) , x(u) ; x(u) , y(v)^2 ];
[vecs(:,:,u,v),vals
(:,:,u,v)] = eig(M(:,:,u,v));
end end
currently that code errors out for me:
parse error near line 6 of file C:\Users\nicholas.jankowski\Desktop\temp\test.m
syntax error
>>> [vecs(:,:,u,v),vals (:,:,u,v)] = eig(M(:,:,u,v));
if I delete the space between "vals (" : x = linspace(0,1,5); for u=1:5 for v=1:5
M = [ y(v)*x(u) , x(u) ; x(u) , y(v)^2 ];
[vecs(:,:,u,v), vals(:,:,u,v)] = eig(M(:,:,u,v));
end end
then I get: error: M(_,_,_,2): but M has size 2x2 error: called from test at line 6 column 36


On Tue, May 5, 2020 at 8:30 PM Nicholas Jankowski < [hidden email]> wrote: currently that code errors out for me:
parse error near line 6 of file C:\Users\nicholas.jankowski\Desktop\temp\test.m
syntax error
>>> [vecs(:,:,u,v),vals (:,:,u,v)] = eig(M(:,:,u,v));
if I delete the space between "vals (" : x = linspace(0,1,5); for u=1:5 for v=1:5
M = [ y(v)*x(u) , x(u) ; x(u) , y(v)^2 ];
[vecs(:,:,u,v), vals(:,:,u,v)] = eig(M(:,:,u,v));
end end
then I get: error: M(_,_,_,2): but M has size 2x2 error: called from test at line 6 column 36
My bad  I started writing this question, tried the MWE, noticed that it didn't work, fixed the code... and apparently forgot to copy the correct code back into the email.
The corrected code is copied below.
x = linspace(0,1,5); y = linspace(2,3,5); for u=1:5 for v=1:5 M(:,:,u,v)=[y(v)*x(u),x(u);x(u),y(v)^2]; [vecs(:,:,u,v),vals(:,:,u,v)] = eig(M(:,:,u,v)); end end
The space after vals must have been a typo after I copied this to Gmail. Aside from that, the only change is that I added
(:,:,u,v) after M inside the loop. When I copy this code out of Gmail. it appears garbled in both Notepad++ and Octave both, so there's probably something strange going on with the formatting. To circumvent that, I also attached the script.

