I am a fortran user and i am currently switching to matlab. I read that to be efficient, it is better to vectorize than using for loops.
How would you vectorize this loop ?
for i=init:fina
a(i,i+nf)=b(i)*c(i);
end
I tried this but it does not work as "a" is a matrix and "b" and "c" are two vectors ; how to include a vector which is not a row or a column in a matrix ?
i=init:fina;
a(i,i+nf)=b(i).*c(i);
And I have also the inverse problem...how to extract a vector from a matrix a(i,i+nf) to be computed with another one like this :
b(i)=a(i,i+nf).*c(i);
Last but not least, the vectorization in these cases will be more efficient than the for loop ?
Kind regards.
FP

댓글 수: 1

Jos (10584)
Jos (10584) 2017년 3월 2일
편집: Andrei Bobrov 2017년 3월 2일
  • What are at the inputs (init, fina, nf, b, c)?
  • Does a exist already? or is it created on the spot?
  • Perhaps you can give a small example of the inputs and the expected output?

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

 채택된 답변

Andrei Bobrov
Andrei Bobrov 2017년 3월 2일
편집: Andrei Bobrov 2017년 3월 2일

0 개 추천

first
a = zeros(fina,fina + nf);
ii = init:fina;
a(sub2ind([fina,fina + nf], ii,ii + nf)) = b(ii).*c(ii);
second
d = diag(a,nf-1);
b(ii) = d(ii)./c(ii);

댓글 수: 1

frenchprion
frenchprion 2017년 3월 2일
Great ! sub2ind and diag are the solutions !
Thanks !
FP

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2017년 3월 2일

댓글:

2017년 3월 2일

Community Treasure Hunt

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

Start Hunting!

Translated by