Multiplication of elements in array
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Cedric
2014-5-12
编辑:Cedric
2014-5-12
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 个评论
更多回答(1 个)
Andrei Bobrov
2014-5-12
编辑:Andrei Bobrov
2014-5-12
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(:);
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!