How do I simplify this code (remove for loop)?

조회 수: 1 (최근 30일)
Josh
Josh 2011년 6월 21일
I'm trying to get in the habit of writing my code in terms of matrix operations and using as few for loops as possible. Is there a better way to write this code without the for loop?
for ii=1:N
if (acos(dot(rel_vec,vec_array(:,ii))) > pi/2)
vec_array(:,ii) = -vec_array(:,ii);
end
end
vec_array is matrix containing N vectors (3xN). I compare each vector in the matrix to make sure they're within 180 degrees of some relative vector (rel_vec). If the vector is more than 180 degrees away, I multiply the vector by -1.

채택된 답변

Oleg Komarov
Oleg Komarov 2011년 6월 21일
idx = acos(rel_vec * vec_array) > pi/2;
rvec(:,idx) = -rvec(:,idx);
where rel_vec is 1 by 3.

추가 답변 (1개)

Josh
Josh 2011년 6월 21일
Yah, that'll do it. I knew there was a much easier way to do it. Thanks!

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by