Vector in a piecewise function
이전 댓글 표시
So, I've trying to learn to use vectors in a piecewise function. I've got the function working properly, (code below). When I use any single number, (pwise(5), it works right. When I use a vector, say, pwise(-5:0:50), it gives me numbers I know are not correct. -5 should be -5, I'm just not sure what MatLab is doing. Any pointers?
function[v]=pwise(t)
%Figures Piecewise Function
if t<0
v=0
elseif t<8
v=10*t^2-5*t
elseif t<16
v=624-5*t
elseif t<26
v=36*t+12*(t-16)^2
else
v=2136*exp(-0.1*(t-26))
end
댓글 수: 1
Image Analyst
2013년 9월 10일
편집: Image Analyst
2013년 9월 10일
What happens when you follow the normal debugging process and step through your code? I bet that would explain things. http://blogs.mathworks.com/videos/2012/07/03/debugging-in-matlab/ And what do you expect to happen when you say "if [-5,-4,-3,-2,-1,0,1,2,3,4,5] < 0"? Do you expect it to automatically somehow form a loop over all those numbers and do the if statement for each number? It doesn't.
채택된 답변
추가 답변 (2개)
Image Analyst
2013년 9월 10일
0 개 추천
Try using .^ instead of ^ so that you square all elements, element by element.
댓글 수: 2
Daniel
2013년 9월 10일
Image Analyst
2013년 9월 11일
Well it does work - it was at least part of the solution, as Roger showed, but not the whole solution. You should really learn when to use the dot in front of the operators.
Sally Al Khamees
2016년 12월 23일
편집: Sally Al Khamees
2017년 2월 21일
0 개 추천
If you have R2016b and the Symbolic Math Toolbox, you can just use the piecewise function with a vector

:
카테고리
도움말 센터 및 File Exchange에서 Code Performance에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!