2014-02-27 145 views
0

我有兩個問題。 我該如何去乘以不同維度的數組?乘以不同尺寸的陣列

Question 1 Example: 

    A1=1,2,3,4,5,6 
    A2=1,2,3 
    The answer I would like to get would be 
    A1*A2 =1,4,9,4,10,18 

我在想使用repmat,但這是最好的方法嗎?

而且

Question 2 Example: 
A1=1,2,3,4,5,6,7 (notice the addition of another value the number 7) 
A2=1,2,3 
The answer I would like to get would be 
A1*A2 =1,4,9,4,10,18,7 (notice the addition of another value the number 7) 

我想for循環,但陣列是非常大的500,000+值和需要很長的時間才能完成。

有沒有辦法編寫一些適用於這兩個問題/示例的matlab /代碼?

+1

1,4,9 ...?我不知道你是如何得到1,4,6 ... –

+0

你在做元素乘法('A1。* A2')嗎?您的代碼表示矩陣乘法('A1 * A2')... – kkuilla

+0

@Mad物理學家感謝您的接觸我將6更改爲9並更新了問題 –

回答

2

可以使用mod循環通過更短的陣列的元素:

result = A1.*A2(mod(0:numel(A1)-1,numel(A2))+1); 

或者,如果一個長是其他(第一實例)的整數倍,則可以reshape較大載體中,從而一個維度中較短向量匹配,然後使用bsxfun

result = bsxfun(@times, reshape(A1,numel(A2),[]), A2(:)); 
result = result(:).'; 
+0

我試過你的代碼 A1 = 1,2,3,4,5,6; A2 = 1,2,3; result = bsxfun(@times,reshape(A1,numel(A2),[]),A2(:)); result = result(:)。' 和 A1 = 1,2,3,4,5,6; A2 = 1,2,3; (mod(0:numel(A1)-1,numel(A2))+ 1); 但我的問題的答案沒有顯示我做了什麼不正確的? –

+1

要定義你的載體'A1'和'A2',你需要使用__brackets__:'A1 = [1,2,3,4,5,6]; A2 = [1,2,3];' –

0

下面是一個代數解,如果A2'*A1尺寸是合理的:

B = spdiags(A2'*A1,0:numel(A2):numel(A1)) 
result = B(1:numel(A1)) 
+0

我試過你的代碼並得到尺寸不匹配 A1 = 1,2,3,4,5,6; A2 = 1,2,3; (A1)* A2,0:numel(A1):numel(A2)) result = B(1:numel(A2)) –

+0

@RickT對不起,我轉換了A1和A2。現在糾正。你也需要A1和A2的括號。 – Bitwise