call function for each combination of rows in A and columns in B
1 次查看(过去 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.
0 个评论
采纳的回答
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
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Performance and Memory 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!