How to vectorize the evaluation of a kernel function.

조회 수: 4 (최근 30일)
Jingyu
Jingyu 2022년 11월 27일
댓글: Jingyu 2022년 12월 5일
I have a kernal function which is defined for . And now I have to compute a matrix for m points and n points , where K is given by . It is direct when using two for loop. But how can I vectorize the evaluation? For example, I tried
k_fun = @(x, y) 1 / norm(x - y);
d = 2; % Make d = 1 if you want it runs correctly.
m = 100;
n = 100;
x_points = rand(m, d);
y_points = rand(n, d);
% The following code is the two for loop version.
K = zeros(m, n);
for i = 1 : m
for j = 1 : n
K(i, j) = k_fun(x_points(i,:), y_points(j, :));
end
end
% The folloing code works when d = 1, but when d > 1 it failes.
K = k_fun(x_points, y_points');
% When d > 1, the error is "Arrays have incompatible sizes for this
% operation."
When , it gives the result I want, But for , it failes. How can I improve it?
  댓글 수: 6
Jan
Jan 2022년 12월 5일
@Jingyu: "I have told you the code will occur error" - yes, you did. Please insert the error message also in future questions.
While your code is vectorized already, you let the readers guess, what you want to achieve. All we know, is that your kernal function is "special" and the not working code.
Jingyu
Jingyu 2022년 12월 5일
@Jan Thanks for your advice. I have changed the code.

댓글을 달려면 로그인하십시오.

채택된 답변

Matt J
Matt J 2022년 11월 27일
K=1./pdist2(x_points,y_points);
  댓글 수: 14
Torsten
Torsten 2022년 11월 28일
Does it mean I must write two for loops?
Yes.
Jingyu
Jingyu 2022년 11월 28일
@Torsten Thanks for your answer!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by