call function for each combination of rows in A and columns in B
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
danielle sisserman
el 30 de Dic. de 2020
Editada: Bruno Luong
el 30 de Dic. de 2020
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 comentarios
Respuesta aceptada
Ameer Hamza
el 30 de Dic. de 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)
2 comentarios
Más respuestas (1)
Bruno Luong
el 30 de Dic. de 2020
Editada: Bruno Luong
el 30 de Dic. de 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.
0 comentarios
Ver también
Categorías
Más información sobre Performance and Memory en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!