## What is the most effieicnt method of multiplying a 2d matrix by a vector to give a 3d matrix?

### Simon (view profile)

on 23 Nov 2012

I want to create a 3D matrix by multiplying all the elements in a 2d matrix by all the elements in a vector to give a 3d matrix.

I initially used this: x=3; y=3; z=4;

```flat = [1,2,3;4,5,6;7,8,9];
deep = [1,2,3,4]';
field=zeros(3,3,4);
```
```tic
for i=1:x
for j=1:y
field(i,j,:)=flat(i,j)*deep;
end
end
toc
Elapsed time is 0.000027 seconds.
```

but thought I could speed it up if I replaced the loop with:

```tic
for i=1:z
field(:,:,i) = flat(:,:)*deep(i);
end
toc
```

Elapsed time is 0.000202 seconds. However, the first method with more loop iterations proved faster. Can anyone explain why and more importantly is there a better, more effieint method than either of these?

Thanks

## Products

on 23 Nov 2012
Edited by Matt J

### Matt J (view profile)

on 23 Nov 2012

For larger data, you'll probably find this version the most efficient

`   field = bsxfun(@times, flat, reshape(deep,1,1,[]) );`

However, the first method with more loop iterations proved faster.

First, the data is way too small for this to be a good test of anything. However, I think the main reason the 2nd version is slower is because you are indexing flat(:,:) unnecessarily. When I modify to

`   field(:,:,i) = flat*deep(i);`

the 2nd version becomes faster for me.

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi test