필터 지우기
필터 지우기

How to simplify a code to remove a for loop and make it faster?

조회 수: 3 (최근 30일)
carlos Uribe
carlos Uribe 2014년 8월 14일
답변: Andrei Bobrov 2014년 8월 14일
Hello,
I'm still learning vectorization and haven't figured out how to simplify this code:
B=zeros(1,a^2);
for j=1:a^2;
B(:)=B(:)+C(:,j)*D(j);
end;
in which B is a vector of 1 row by a^2 columns, C is an a x a matrix, and D is a vector of 1 row by a^2 columns
So basically what is happening is I take all the columns of C (one by one) and multiply them by D and then add them to B but this is repeated column by column on C.
I appreciate if anyone can show me how to do this.
Thank you very much.

답변 (3개)

Iain
Iain 2014년 8월 14일
One of these ought to do it:
B = C' * D;
or
B = C' * D';
You might need to transpose B to get what you want....

Azzi Abdelmalek
Azzi Abdelmalek 2014년 8월 14일
편집: Azzi Abdelmalek 2014년 8월 14일
Edit
a=4
C=rand(a^2);
D=rand(1,a^2);
B=sum(bsxfun(@times, C,D),2)
  댓글 수: 2
carlos Uribe
carlos Uribe 2014년 8월 14일
sorry my bad...C is an a^2 x a^2 array
Azzi Abdelmalek
Azzi Abdelmalek 2014년 8월 14일
편집: Azzi Abdelmalek 2014년 8월 14일
Look at edited answer

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


Andrei Bobrov
Andrei Bobrov 2014년 8월 14일

카테고리

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

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by