MATLAB Answers

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

7 views (last 30 days)
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.

Accepted Answer

Ameer Hamza
Ameer Hamza on 30 Dec 2020
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)

More Answers (1)

Bruno Luong
Bruno Luong on 30 Dec 2020
Edited: Bruno Luong on 30 Dec 2020
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.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by