0

Let

input = [0 0 0 5 5 7 8 8];

I now want to transform this vector into the form

output = [3 3 3 3 5 5 6 8];

Which basically is a stairs plot.

Explanation

The input vector is used to plot data points along the x-axis. The y-axis is thereby provided by 1:length(input). So the resulting plot shows the cumulative number of datapoints along the y-axis and the time of occurrence along the x-axis.

I now want to fit a model against my dataset. Therefor I need a vector that provides the correct value for a certain time (x-value).

The desired output vector basically is the result of a stairs plot. I am looking for an efficient way to generate the desired vector in matlab. The result of

[x, y] = stairs(input, 1:length(input));

did not bring me any closer.

Cœur
  • 37,241
  • 25
  • 195
  • 267
sge
  • 7,330
  • 1
  • 15
  • 18

1 Answers1

2

It can be done with bsfxun as follows:

x = [0 0 0 5 5 7 8 8];
y = sum(bsxfun(@le, x(:), min(x):max(x)), 1);

This counts, for each element in 1:numel(x), how many elements of x are less than or equal to that.

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • Replacing 1:numel(x) with 1:max(x) did the job! Thank you very much. Very nice solution! – sge Oct 14 '15 at 13:35
  • Ah, I misunderstood your question. Shouldn't it then be `y = sum(bsxfun(@le, x(:), min(x):max(x)), 1)`? (considering `x = [2 2 2 5 5 7 8]` for example) – Luis Mendo Oct 14 '15 at 13:43
  • You are correct. In case min(x) is different from 1 the result would have leading zeros. Thanks again! – sge Oct 14 '15 at 13:47