Calculating all combinations of vector-element multiplication
조회 수: 13 (최근 30일)
이전 댓글 표시
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???
댓글 수: 0
채택된 답변
James Tursa
2018년 6월 5일
편집: James Tursa
2018년 6월 5일
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
James Tursa
2018년 6월 5일
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.
추가 답변 (1개)
Sid Parida
2018년 6월 5일
편집: Sid Parida
2018년 6월 5일
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.
참고 항목
카테고리
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!