call function for each combination of rows in A and columns in B

1 ビュー (過去 30 日間)
danielle sisserman
danielle sisserman 2020 年 12 月 30 日
編集済み: Bruno Luong 2020 年 12 月 30 日
Xtrain = [1 2; 3 4; 5 6];
Xtest = [7 8 ; 9 10];
kernel = @(x1,x2) norm(x1 - x2);
m = size(Xtrain, 1);
n = size(Xtest,1);
kernels = kernel(Xtest, Xtrain);
I want "kernels" to be the following matrix:
kernels = [ kernel( [7 8] ,[ 1 2] ) kernel([7 8] ,[3 4] ) kernel([7 8] ,[5 6] )
kernel([9 10] , [1 2] ) kernel([9 10] ,[3 4]) kernel( [9 10] ,[5 6] )]
How can I call the kernel function properly so that I will get back this matrix?
Thank you.

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 12 月 30 日
Try this
Xtrain = [1 2; 3 4; 5 6];
Xtest = [7 8 ; 9 10];
kernel = @(x1,x2) norm(x1 - x2);
m = size(Xtrain, 1);
n = size(Xtest, 1);
XtrainC = mat2cell(Xtrain, ones(m,1), 2);
XtestC = mat2cell(Xtest, ones(n,1), 2);
[R, C] = ndgrid(1:n, 1:m);
kernels = arrayfun(@(r, c) kernel(XtestC{r}, XtrainC{c}), R, C)
  2 件のコメント
Ameer Hamza
Ameer Hamza 2020 年 12 月 30 日
I am glad to be of help!

サインインしてコメントする。

その他の回答 (1 件)

Bruno Luong
Bruno Luong 2020 年 12 月 30 日
編集済み: Bruno Luong 2020 年 12 月 30 日
Simple for-loop is 3-4 times faster than fancy MATLAB pseudo vectorization, and much more readable
Xtrain = rand(1000,2);
Xtest = rand(1000,2);
kernel = @(x1,x2) norm(x1 - x2);
m = size(Xtest,1);
n = size(Xtrain,1);
tic
kernels = zeros(m,n);
for i=1:m
for j=1:n
kernels(i,j) = kernel(Xtest(i,:),Xtrain(j,:));
end
end
toc % Elapsed time is 1.389989 seconds.
tic
XtrainC = mat2cell(Xtrain, ones(m,1), 2);
XtestC = mat2cell(Xtest, ones(n,1), 2);
[R, C] = ndgrid(1:n, 1:m);
kernels = arrayfun(@(r, c) kernel(XtestC{r}, XtrainC{c}), R, C);
toc % Elapsed time is 5.821724 seconds.

カテゴリ

Find more on Matrices and Arrays in Help Center and File Exchange

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by