0
假設我有兩個數組X和Y,我需要一個矩陣M(i,j)= some_func(X(i),Y(j))。我怎樣才能不使用循環?笛卡爾乘積的Matlab向量化
假設我有兩個數組X和Y,我需要一個矩陣M(i,j)= some_func(X(i),Y(j))。我怎樣才能不使用循環?笛卡爾乘積的Matlab向量化
最好的答案是使用bsxfun,如果它是一個選項。按照幫助bsxfun,它完全可以在任何普通的二元函數,只要:
FUNC can also be a handle to any binary element-wise function not listed
above. A binary element-wise function in the form of C = FUNC(A,B)
accepts arrays A and B of arbitrary but equal size and returns output
of the same size. Each element in the output array C is the result
of an operation on the corresponding elements of A and B only. FUNC must
also support scalar expansion, such that if A or B is a scalar, C is the
result of applying the scalar to every element in the other input array.
如果你的函數只接受標量輸入,然後循環是簡單的替代品。
很難回答你的模糊問題,它最終取決於你的功能。您可以做的是使用meshgrid
然後執行操作,通常使用點運算符
x = 1:5;
y = 1:3;
[X,Y] = meshgrid (x,y)
M = X.^Y;