One other trick is to use ind2sub
and sub2ind
. In conjunction with numel
and size
, this can let you do stuff like the following, which creates an N-dimensional array, and then sets all the elements on the "diagonal" to be 1.
d = zeros( 3, 4, 5, 6 ); % Let's pretend this is a user input
nel = numel( d );
sz = size( d );
szargs = cell( 1, ndims( d ) ); % We'll use this with ind2sub in the loop
for ii=1:nel
[ szargs{:} ] = ind2sub( sz, ii ); % Convert linear index back to subscripts
if all( [szargs{2:end}] == szargs{1} ) % On the diagonal?
d( ii ) = 1;
end
end