In my above examples, I'm assuming x is being passed as a vector (which may have 1 or more elements). I currently can't access the docs, which may contain the answer. For me, your code all works anyway (2015b)! My guess is that this is something to do with how fplot is calling your functions. So, with a similar (but even simpler) approach to f2 as well, function y = f1(x)Īs for your mysteries when changing part of the piecewise function and everything working. Y = coef.*x + 2 % Coeff can be done in-line without being declared coef = (x < 0)*2 - 1 % For the above example, coef = Now it can be seen how this can be done in a one liner. Y(x<0) = x + 2 % Assign values of y, where x<0, to x + 2 Y = -x + 2 % Initialise variable y, assign its values to -x + 2 by default If the course material can be changed / extended, then a much better option in Matlab is to leverage logical indexing. % "if x < 0" is the same as "if all(x < 0)" = false, so if statement skipped This is because otherwise you may have the following issue: x = Y = zeros(size(x)) % Initialise y to the correct sizeįor ii = 1:numel(x) % Loop through elements of x (and so y) You say that you want to specifically use an if structure, in which case you will have to evaluate each element of the input vector in turn function y = f1( x )
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |