From: Alvaro Canivell on
Hi all

Is there a straight way to create an 3D (or N-D, where N>2) identity matrix, as you can do with e.g.:

eye(4,4)

So far I have been doing:

A = zeros(4,4,4)
for i=1:4
A(i,i,i)=1;
end

But I maybe that for huge data sets it may not be the best (?)

Thnx
From: Jan Simon on
Dear Alvaro!

> Is there a straight way to create an 3D (or N-D, where N>2) identity matrix, as you can do with e.g.:
>
> A = zeros(4,4,4)
> for i=1:4
> A(i,i,i)=1;
> end

A = zeros(n, n, n);
n3 = n*n*n;
A([1:(n3 / (n-1)):n3]) = 1;

This is slightly faster than: A(linspace(1, numel(A), n)) = 1;
You can generalize this to more than 3D easily.

Good luck, Jan