Effacer les filtres
Effacer les filtres

Multiplication of elements in array

2 vues (au cours des 30 derniers jours)
Grace
Grace le 12 Mai 2014
Modifié(e) : Cedric le 12 Mai 2014
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

Réponse acceptée

Cedric
Cedric le 12 Mai 2014
Modifié(e) : Cedric le 12 Mai 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.

Plus de réponses (1)

Andrei Bobrov
Andrei Bobrov le 12 Mai 2014
Modifié(e) : Andrei Bobrov le 12 Mai 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(:);
  2 commentaires
Grace
Grace le 12 Mai 2014
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 le 12 Mai 2014
corrected

Connectez-vous pour commenter.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by