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

조회 수: 3 (최근 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)

추가 답변 (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.

카테고리

Help CenterFile Exchange에서 Just for fun에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by