MATLAB: Multiplication of elements in array

arraymatrixmultiplication

Hi everyone, I have b=[1 1 1; 1 2 4; 1 3 9; 1 4 16] and k=1:5, I want to have 4 different set of numbers.
There are total 4 rows in set b.
To form the first set of number which denoted as kb1, I take the numbers from first row from set b, which is [1 1 1].
For the first row of kbl=k(1)*[1 1 1]
For the second row of kb1=k(2)*[1 1 1]
For the third row of kbl=k(3)*[1 1 1]
For the fourth row of kb1=k(4)*[1 1 1]
And finally for the fifth row of kbl=k(5)*[1 1 1].
Next follow by second set of the numbers,which denoted as kb2=k*[1 2 4]
So at the last I will have 4 set of numbers,
How can i do this?
Thanks

Best Answer

And if you aren't too familiar with Andrei's singleton expansion in 3D numeric arrays ;-), here is a simpler and less compact solution, which creates a cell array of results..
nRows = size( b, 1 ) ;
% Initialize (prealloc) cell array of results.
kbs = cell( nRows, 1 ) ;
% Loop over rows of b and build kdbs.
for rId = 1 : nRows
kbs{rId} = bsxfun( @times, k(:), b(rId,:) ) ;
end
Then, to get e.g. what you would name kb3, you index teh content of cell #3 of the cell array kbs:
>> kbs{3}
ans =
1 3 9
2 6 18
3 9 27
4 12 36
5 15 45
Note that in the clal to BSFUN, k(:) is a k developed as a column vector, and b(rId,:) is a row vector of elements of row rId of b:
>> k(:)
ans =
1
2
3
4
5
>> b(3,:) % Row 3 for example.
ans =
1 3 9
Then what BSXFUN does roughly is to repeat both vectors as many times as there are rows/columns in the other vector (along the non-singleton dimension) to generate (internally) the following arrays:
1 1 1 1 3 9
2 2 2 1 3 9
3 3 3 1 3 9
4 4 4 1 3 9
5 5 5 1 3 9
These arrays are then multiplied element by element, as you passed @times - a handle on the element-wise multiplication - as the first argument in the call to BSXFUN.