Info

How to impliment this without loop?

1 view (last 30 days)
Dimitrios on 26 Nov 2014
Closed: MATLAB Answer Bot on 20 Aug 2021
I need to take the rate of change of a variable and for the first value there is not a previous value to take.For the initial i assumed that the rate of change is zero as the simulation is so long that it will not affect the results.So i tried something like this:
Ofcurse its not running cause there is no zero index.I know it can be done by a loop but I would prefer something more elegant.Any idea?

Henrik on 27 Nov 2014
You example is a bit confusing to me, there seems to be several unnecessary complications, e.g. using fields.
Anyway, here's what I would do:
I'd even guess that this will work, depending on exactly what you need.
rate=(obj.Value(2:end,:)-obj.Value(1:end-1,:))/timestep;
If you want rate to be the same size as obj.Value, you could also do
rate=zeros(size(obj.Value));
rate(2:end,:)=(obj.Value(2:end,:)-obj.Value(1:end-1,:))/timestep;
I hope this can be used?
You can also look up diff, that might be helpful.