Filter löschen
Filter löschen

Calculating all combinations of vector-element multiplication

13 Ansichten (letzte 30 Tage)
I have N vectors of varying size for which I wish to compute the product of every element.
A = [1 2 3 4]
B = [1]
C = [10 20]
Desired result = [a1*b1*c1 a1*b1*c2 a2*b1*c1 a2*b1*c2...] --> size = 1 x 8
I have found a few post for the 2 vector case in which simple vector multiplication works
D = A'*B --> this results in a matrix, but the entries align with what I am trying to achieve.
Expanding this to a 3-vector problem I had some success with bsxfun
D = bsxfun(@times,A'*B,reshape(C,1,1,numel(C))); --> this results in a 3-D matrix
How do you do this for more than 3 vectors, lets say 10, without using embedded 'for' loops???

Akzeptierte Antwort

James Tursa
James Tursa am 5 Jun. 2018
Bearbeitet: James Tursa am 5 Jun. 2018
I don't know how to avoid a loop of some sort for an arbitrary number of variables, even if it is hidden in the background. E.g., a function approach:
function result = timesall(varargin)
if( nargin > 0 )
result = varargin{1};
for k=2:nargin
result = result(:) * reshape(varargin{k},1,[]);
end
result = reshape(result,1,[]);
else
result = [];
end
end
And a sample run:
>> A = [1 2 3 4]
A =
1 2 3 4
>> B = [1]
B =
1
>> C = [10 20]
C =
10 20
>> timesall(A,B,C)
ans =
10 20 30 40 20 40 60 80
  4 Kommentare
Still Learning Matlab
Still Learning Matlab am 5 Jun. 2018
Could I use this function in conjunction with a tallarray? basically populate the tall array in batches using a function (or embed it within a for loop)
James Tursa
James Tursa am 5 Jun. 2018
That (or similar) strategy is just an attempt to solve the memory issue, and it doesn't really solve it since you are still talking about 7 petabytes (either in memory or on disk). And it doesn't address the processing time aspect at all. Maybe you can start a new Question thread that states your problem, and people can suggest ways to approximate a solution that will fit in the memory you have and run in a reasonable amount of time.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Sid Parida
Sid Parida am 5 Jun. 2018
Bearbeitet: Sid Parida am 5 Jun. 2018
Not sure of internal tools but use the two files attached above (found on File Central) and use the following code:
a = [1 2 3 4]
b = [1]
c = [10 20]
D = prod(cartprod(a, b, c), 2)'
D should contain the desired result. It works for higher number of vectors too.
  1 Kommentar
Still Learning Matlab
Still Learning Matlab am 5 Jun. 2018
This worked okay, unless the input vector has a duplicate element (i.e. if you change a = [1 2 3 1] it throws an error).

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by