How to improve the code for vector calculation
2 views (last 30 days)
Show older comments
clear all
clc
NG=3;
B_area=rand(12,3);
P=rand(1,12)
P1=P(1:3);P2=P(4:6);P3=P(7:9);P4=P(10:12);
B_area1=B_area((1:3),:);
B_area2=B_area((4:6),:);
B_area3=B_area((7:9),:);
B_area4=B_area((10:12),:);
for i=1:NG
for j=1:NG
PL_area1(j)=P1(i).*B_area1(i,j).*P1(j);
PL_area2(j)=P2(i).*B_area2(i,j).*P2(j);
PL_area3(j)=P3(i).*B_area3(i,j).*P3(j);
PL_area4(j)=P4(i).*B_area4(i,j).*P4(j);
end
eval(['PL_area1' num2str(i) '=(PL_area1)']);
eval(['PL_area2' num2str(i) '=(PL_area2)']);
eval(['PL_area3' num2str(i) '=(PL_area3)']);
eval(['PL_area4' num2str(i) '=(PL_area4)']);
end
PL_area1=sum(PL_area11(:,:)+PL_area12(:,:)+PL_area13(:,:));
PL_area2=sum(PL_area21(:,:)+PL_area22(:,:)+PL_area23(:,:));
PL_area3=sum(PL_area31(:,:)+PL_area32(:,:)+PL_area33(:,:));
PL_area4=sum(PL_area41(:,:)+PL_area42(:,:)+PL_area43(:,:));
PL=[PL_area1 PL_area2 PL_area3 PL_area4]
0 Comments
Answers (2)
Andrei Bobrov
on 13 Jun 2013
B = rand(12,3);
P = rand(1,12);
Ba = permute(reshape(B,3,4,[]),[1 3 2]);
Pn = reshape(P,3,1,[]);
Pa = bsxfun(@times,Pn,reshape(Pn,1,3,[])).*Ba;
PL = sum(reshape(Pa,[],4));
Iain
on 13 Jun 2013
Inner looop can be replaced by:
PL_area4=P4(i).*B_area4(i,:).*P4(:); etc.
The outer loop cannot be replaced unless you can formulate your mathematics into a matrix form.
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!