how to vectorize squared function

조회 수: 1 (최근 30일)
Maximilian Dio
Maximilian Dio 2021년 7월 22일
편집: Bruno Luong 2021년 7월 22일
Hi I have a problem considering calculating a squared function of a grid
so I have 2 vectors X=rand(N,D) and Y=rand(M,D)
I want to generate a function that returs a matrix s.t.
for i = 1:N
for j = 1:M
r2(i,j) = (X(i,:)-Y(j,:))*L*(X(i,:)-Y(j,:))';
end
end
is there a way to vectorize this cleverly?
It needs to run in Simulink (code generation)

답변 (2개)

KSSV
KSSV 2021년 7월 22일
r2 = (X-Y).*L.*(X-Y)';

Bruno Luong
Bruno Luong 2021년 7월 22일
편집: Bruno Luong 2021년 7월 22일
X=rand(3,10);
Y=rand(4,10);
L=rand(10);
N=size(X,1);
M=size(Y,1);
XX=reshape(X,N,1,[]);
YY=reshape(Y,1,M,[]);
YX=reshape(XX-YY,N*M,[]);
r2=reshape(sum(YX.'.*(L*YX')),[N M])
r2 = 3×4
-0.0902 0.5037 1.1533 1.2152 0.2232 0.4179 1.9723 1.8407 0.4105 -0.1182 2.4237 3.2231

카테고리

Help CenterFile Exchange에서 Simulink에 대해 자세히 알아보기

태그

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by