0
votes

I want to make an .m file that represents a piece wise function and returns a vector with all the discrete values calculated.

To be a bit more clear, I want a function (which I have named Iapp and is time dependant, so Iapp(t)) that returns zero for the first 100s then returns 0.5 for 100-120s then again zero for 120-220s then 0.5+0.2 for 220-240s and that goes on.

I know a piece wise function can be defined using logical indexing, but my problem is that my time interval for which I want the function is not predefined. So I don't know how logical indexing could work...if the time interval is not a multiple of 120 it doesn't work.

I have tried the following:

function Vect_Iapp = Iapp_morceaux(tspan, h)
i = 1;
j = 1;
t = tspan(1):h:tspan(2);
while t(i) < tspan(2)         
    while(t(i)< (j*100 + (j-1)*20))
        Iapp(i) = 0;
        i = i + 1;
    end
    while (t(i)>j*100 && t(i) < j*100 + j*20)
        Iapp(i) = 0.5 + j*0.2;
        i = i + 1;
    end
    j = j + 1;
end    
Vect_Iapp = Iapp;
end

But the algorithm does not always work like it should. Any ideas as to how this function could be defined? Note that I would also like to be able to somehow give a scalar value for tspan and make the function return just a scalar value back.

2
To me it is not clear yet, what the function should do (which you say it does not at the moment). Is tspan usually two-component?oliver
Yeah tspan = [Initial_time Final_time]. For example if tspan = [0 240] then it should be Iapp(0-100) = 0, Iapp(101 - 120) = 0.5, Iapp(121 - 220) = 0, Iapp(220 - 240) = 0.7Desperados
And if tspan = [17 241] ?oliver
Following my reasoning it should have been Iapp(17 - 117) = 0, Iapp(117 - 137) = 0.5, Iapp(137-141) = 0... . But in my application the intervalle will always start from 0, this is why I wrote the algorithm like that. I guess I could add '+tspan(1)' in the conditions and it would be the same.Desperados

2 Answers

1
votes

I'm afraid I don't get the purpose of the convoluted loops, but from what I seem to understand, you can deduce the lengths nk of the k'th partial vectors and their values xk from the function parameters. Then why not do this in the beginning and just create every partial vector by something like

iappk = xk*ones(1,nk);

and finally concatenate them all together

Iapp = [iapp1 iapp2 iapp3 iapp4]

I hope it helps you.

0
votes

This function?

x=linspace(0,600,1000);
y=Iapp(x);
plot(x,y)

function y=Iapp(t)
    r=mod(t,120);
    c=floor(t/120);
    VAL1=0;
    VAL2=0.5 + 0.2*c;
    y=VAL1.*(r<=100) + VAL2.*(r>100);
end

enter image description here