## Integration of piecewise function with integral

### Lukas (view profile)

on 6 May 2013

Hi, I have piecewise function J(t,m).

function [j] = functionJ (t,m)

model = @(t) -(0.0008.*m./(-0.01-0.07.*exp(-2.*t))-0.000112.*m.*t.*exp(-2.*t)./(-0.01-0.07.*exp(-2.*t)).^2).*exp(0.0008.*m.*t./(-0.01-0.07.*exp(-2.*t)));

j = (t<20).*((1/20)*integral(model,0,t)) + (t>=20).*((1/20)*integral(model,(t-20),t)); end

Now I need another function R(x,m) to integrate J in respect to t from 0 to x I'm still new with Matlab. Could you please give me hint how to do that?

## Products

No products are associated with this question.

### Youssef Khmou (view profile)

on 6 May 2013

hi, try

` doc quad`
` doc trapz`

### Andrei Bobrov (view profile)

on 6 May 2013
Edited by Andrei Bobrov

### Andrei Bobrov (view profile)

on 7 May 2013

```function J = R(f,x,m)
t = x >= 20;
p = zeros(numel(x),1);
p(t) = x(t) - 20;
J = arrayfun(@(x,y)integral(@(t)f(t,m),y,x),x,p);
```

eg use:

```f = @(t,m) -(0.0008.*m./(-0.01-0.07.*exp(-2.*t))-0.000112.*m.*t.*exp(-2.*t)./...
(-0.01-0.07.*exp(-2.*t)).^2).*exp(0.0008.*m.*t./(-0.01-0.07.*exp(-2.*t)));
```
```m = 1;
```
```x = randi(40,20,1);%eg
```
```out = R(f,x,m)
```

OR

```function J = R(x,m)
t = x >= 20;
p = zeros(numel(x),1);
p(t) = x(t) - 20;
f = @(t,m) -(0.0008.*m./(-0.01-0.07.*exp(-2.*t))-0.000112.*m.*t.*exp(-2.*t)./...
(-0.01-0.07.*exp(-2.*t)).^2).*exp(0.0008.*m.*t./(-0.01-0.07.*exp(-2.*t)));
J = arrayfun(@(x,y)integral(@(t)f(t,m),y,x),x,p);
```

```function J = pwint(x,m)
f = @(t,m) -(0.0008.*m./(-0.01-0.07.*exp(-2.*t))-0.000112.*m.*t.*exp(-2.*t)./...
(-0.01-0.07.*exp(-2.*t)).^2).*exp(0.0008.*m.*t./(-0.01-0.07.*exp(-2.*t)));
t = x >= 20;
p = zeros(numel(x),1);
p(t) = x(t) - 20;
J = arrayfun(@(x,y)integral(@(t)f(t,m),y,x),x,p);
```

eg use:

```R = @(x,m)arrayfun(@(t)integral(@(x)pwint(x,m),0,t,'ArrayValued',true),x);
m = 1;
out = R([30,15],m);
```

Lukas

### Lukas (view profile)

on 6 May 2013

Thank you for the answer. But this gives me the same result as function J(t,m). I need to integrate J(t,m).

Andrei Bobrov

### Andrei Bobrov (view profile)

on 7 May 2013

#### Join the 15-year community celebration.

Play games and win prizes!

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi