How to vectorize extraction of relevant sections from multidimensional matrix?

The purpose of the attached code is to interpolate a function over multiple nodes and assign weights to the interpolated values. As you can see I am using many for loops. I have used reshape and repmat methods for other sections of my script but I am stuck in the lines that I am attaching to this question. I would appreciate if you can provide me some guidance to vectorize this. If the code is messy or the description is not clear please let me know. Thank you.
nodes = 5;
age_max = [15 1 1];
% Create a gridded interpolant function
F = griddedInterpolant({agp,tcp,pcp,1:max(age_max),1:lu_bdry,1:no_parcels},Vinit,'spline');
% Interpolate at different quadrature nodes (vectors cx_agp, cx_tcp...)
V_hat = F({cx_agp, cx_tcp, cx_pcp, 1:max(age_max), 1:lu_bdry, 1:no_parcels});
% Assign weights to each interpolated values
w_V_hat = zeros*V_hat;
for j = 1:size(cw_agp,1)
for jj = 1:size(cw_tcp,1)
for jjj = 1:size(cw_pcp,1)
w_V_hat(j,jj,jjj,:,:) = V_hat(j,jj,jjj,:,:)*cw_agp(j)*cw_tcp(jj)*cw_pcp(jjj);
end
end
end

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2013년 2월 25일
편집: Andrei Bobrov 2013년 2월 25일
[a1,a2,a3] = ndgrid(cw_agp,cw_tcp,cw_pcp);
z = a1.*a2.*a3;
s = size(V_hat);
w_V_hat = V_hat.*repmat(z,[1 1 1 s(4:5)]);
or
[a1,a2,a3] = ndgrid(cw_agp,cw_tcp,cw_pcp);
z = a1.*a2.*a3;
w_V_hat = bsxfun(@times,V,z)

댓글 수: 1

Thank you very much for taking the time to answer my question. I had figure out the use of ngrid to simplify the code this way
[a1,a2,a3] = ...
ndgrid(cw_agp,cw_tcp,cw_pcp,1:max(age_max),1:lu_bdry,1:no_parcels);
z = a1.*a2.*a3;
w_V_hat = V_hat.*z
which takes practically the same time to run as the one using bsxfun.
Given the size of the arrays that I am using, the option based on repmat consumes a lot of memory and slows down the computation significantly.
Thank you very much for your guidance.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by