In article <fnvcb6$8g
...@fred.mathworks.com>,
Robert <robert.clement.stops
...@ed.ac.uk> wrote:
>I am trying to insert a vector into a 3D matrix at specified
>locations based on the values in a 2D matrix. I am
>currently looping through the row column positions obtained
>from the 2D matrix and reshaping the 1D matrix to assign it
>to the 3D matrix.
> My2D = round(10.*rand(10,10));
> My1D = rand(100,1);
> My3D = zeros(10,10,100);
> [r c] = find(My2D == 5);
> d = length(My1D);
> for ix = 1:size(r)
Better (or at least clearer) would be size(r,1) instead of size(r)
> rx = r(ix);
> cx = c(ix);
> My3D(rx,cx,:) = reshape(My1D,1,1,d);
You do not need the reshape there.
> end
>This code works fine but I would like to know if there is a
>way to speed up this assignment by using the single index
>vector from the find statement to assign multiple 1D vectors
> to the 3D vector in a single step?
The target indices in My3D are:
bsxfun(@plus, ...
(0:size(My1D,1)).*(size(My3D,1)*size(My3D,2)), ...
sub2ind(size(My3D),r,c,repmat(1,10,1)))
to which you would assign
repmat(My1D,1,size(r,1)).'
You can do this in a single step without reshaping,
My3D(bsxfun(.....)) = repmat(....);
--
"No one has the right to destroy another person's belief by
demanding empirical evidence." -- Ann Landers