How to vectorize this function?

조회 수: 15 (최근 30일)
Quinten Lodewijks
Quinten Lodewijks 2017년 3월 17일
편집: Quinten Lodewijks 2019년 7월 9일
Hello,
i'm new to matlab so this could have a really easy solution but a google search didn't solve my question.
this is the function:
function [angle]= give_angle(position)
if position <= -2 && position > -4
angle = 11.31;
else
angle = 0;
end
end
now if "position" would be a vector lets say: position = -2:0.1:2 it gives the error: Operands to the and && operators must be convertible to logical scalar values.
I tried to replace && with & but then this error comes up: Output argument "angle" (and maybe others) not assigned during call to "give_angle".
All help will be appreciated!

답변 (1개)

David Goodmanson
David Goodmanson 2017년 3월 17일
Hello Quinten, a standard way to do this is to make a vector of zeros the same length as 'position', then make a logical index vector of 1's and 0's for whether the condition is met or not, then change the angle when the condition is met.
angle = zeros(size(position)); % automatically satisfies 'not met' condition
ind = position <= -2 & position > -4;
angle(ind) = 11.31;
  댓글 수: 1
Quinten Lodewijks
Quinten Lodewijks 2017년 3월 18일
okay i get what you are saying, however i didn't post the full code as i thought it wasn't necessary.
but in the full code there are more condition: not only: if position <= -2 && position > -4
but also: elseif position > -2 && position < 0
and also: elseif position > 0 && position < 2

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

카테고리

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