Create a d-dimensional tensor dynamically
问题 I would like to create a d-dimensional tensor using d as an input and without the if statement as below: if d == 2 B = zeros(r,r); for i = 1:r B(i,i) = 1; end elseif d == 3 B = zeros(r,r,r); for i = 1:r B(i,i,i) = 1; end end Is there a more efficient way? 回答1: You can use accumarray: f = @(d,r)accumarray(repmat((1:r).',1 , d), 1); > f(2,5) = 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 Here is the basic signature of accumarray: accumarray( subs , val ) Using accumarray we can create an n