0

How to plot the equation below in Matlab. There are two factors in this equation.

Note that k is a scalar number in (-1,1).

So given an x value, a double value (-infinity,+infinity).

I need to plot a graphic of this function.

if x>0              plot (1-k)x
else (case x<=0)    plot(1+k)x
Igoto
  • 21
  • 5
  • Possible duplicate of [How to make a graph of a three-branches function in matlab](http://stackoverflow.com/questions/30790802/how-to-make-a-graph-of-a-three-branches-function-in-matlab) – Dev-iL Nov 20 '16 at 09:24

2 Answers2

0

Hope this helps

k = 3 - randi(3); %random number between -1-0-1 (thanks op)
x = -1e6:1e6; %a very long vecot
y = zeros(1,length(x)); %prelocate y
ind = find(x); %find the indeces where x>0
y(ind) = (1- k) * x(ind);
ind = find (x<=0);
y(ind) = (1+k) * x(ind);
plot(x,y);%plot
  • Hey nice @Ronen Cohen, but using your version to a float value in [-1,1], doesnt work very well, cause you make ans vector 2x2, and will be a error using it. If I want simulate the integer state, and this case k={-1,0,1}, I'm using randi(3)-2. Thank you for want to help me! ans = 0.5315 -0.4685 -0.4685 0.5315 >> (rand*(-1))^(randi(1,2)) – Igoto Nov 20 '16 at 13:02
0

I like anonymous functions - can improve readability.

f = @(x,k) (1-k).*x.*(x>0) + (1+k).*x.*(x<=0)
plot(x,f(x,k))

Note the use of (x>0) and (x<=0) to handle different cases.

vindarmagnus
  • 326
  • 3
  • 10
  • Could I use your code to plot in Matlab? I dont know this form using @, is it a parametric way? – Igoto Nov 20 '16 at 13:17
  • https://se.mathworks.com/help/matlab/matlab_prog/anonymous-functions.html – vindarmagnus Nov 20 '16 at 13:18
  • Yes you can. Just define x and k to something first. – vindarmagnus Nov 20 '16 at 13:18
  • My problem is that I want plot every case for this function, k={-1,0,1} and x being a point continuous value in [-1000, 1000] just for test. I think I need three plots one for each case of k. – Igoto Nov 20 '16 at 13:23