Multiplication of elements in array
3 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Cedric
on 12 May 2014
Edited: Cedric
on 12 May 2014
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.
0 Comments
More Answers (1)
Andrei Bobrov
on 12 May 2014
Edited: Andrei Bobrov
on 12 May 2014
kb = bsxfun(@times,permute(b,[3,2,1]),k(:));
add
kb = num2cell(bsxfun(@times,permute(b,[3,2,1]),k(:)),[1 2]);
kb_cell = kb(:);
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!