Multiplication of elements in array

2 ビュー (過去 30 日間)
Grace
Grace 2014 年 5 月 12 日
編集済み: Cedric 2014 年 5 月 12 日
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

採用された回答

Cedric
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.

その他の回答 (1 件)

Andrei Bobrov
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(:);
  2 件のコメント
Grace
Grace 2014 年 5 月 12 日
Hi Andreo,
Sorry, this is not what I want to get.
The following are the one that I wish to get:
For kb1=[1 1 1;1 1 1; 1 1 1; 1 1 1;1 1 1]
For kb2=[1 2 4; 1 4 8; 3 6 12; 4 8 16; 5 10 20]
For kb3=[1 3 9; 2 6 18; 3 9 27; 4 12 36; 5 15 45]
For kb4=[1 4 16; 2 8 32; 3 12 48; 4 16 64; 5 20 80]
Thanks.
Andrei Bobrov
Andrei Bobrov 2014 年 5 月 12 日
corrected

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by