Reputation: 31
I've done a few simple matlab-functions before, but for some reason unknown to me, what I'm trying to do now won't work.
The function simply looks like this:
function a = calc(t)
if t < 2.0
a = -pi/2;
else
a = 2*pi;
end
I try calling it by:
a = calc(linspace(0,5))
which (as I have understood it before at least) should generate a matrix of variables with the values of a. However, a simply becomes a constant with the value 2*pi. Why won't it register what happens before t >= 2? Right now it seems like it only calculates the last value (when t = 5). Can someone please tell me what I am doing wrong?
Upvotes: 2
Views: 60
Reputation: 104493
The reason why it isn't working is because your function is only designed to output one value. Naturally, MATLAB will work from the beginning of the array to the end, and so because your function only outputs one value, it will only give you the output of the last value in your array (a.k.a. 5). As such, if you want to do this for a vector / matrix of values, you need to make sure that your output value a
is also of the same type. In other words, do something like this:
function a = calc(t)
a = 2*pi*ones(size(t));
a(t < 2.0) = -pi/2;
Let's go through this one slowly. a
is an array / matrix of values that is the same size as the input t
and every value in a
is set to 2*pi
. After, any values where t < 2.0
, we will change the values to -pi/2
. Anything else, they will stay the same (i.e. 2*pi
). Remember, when you're working with MATLAB, you need to make sure that your output can accommodate for inputs of different shapes and sizes. It's a different way of thinking in comparison to other programming languages that people have dealt with, but once you get the hang of it, it's really easy.
Upvotes: 5