Question
I looking for help to convert countinous form of data into discreate steps form. Here is the example, please help me to ffind solution. X = [ 1 3 5 8 10 15 20 25 30 34 38 40 45 50 55 60 65 69 70] y =[ 1 3 5 4 6 5 8 7 6 7 6 7 6 7 6 7 5 7 0 1] I want convert X variable in to steps multiple of 5 [0 5 10 15 20 25..] and coresspong values of y betwen these steps should be mean(y). Well I am looking for output in the following format. x= [5,10,15...] y=[3,5,5..]. I tried with find(x<5), which gave me indices for calculating the mean (y), but its too laborous method.
Related Questions
Expert Answer
John Williams
PhD Expert
Answered Nov 20, 2025
To convert continuous data into discrete steps and compute the mean of the corresponding yy-values within each step, you can automate the process efficiently using a simple approach in MATLAB.
MATLAB Solution
% Input data
X = [1, 3, 5, 8, 10, 15, 20, 25, 30, 34, 38, 40, 45, 50, 55, 60, 65, 69, 70];
y = [1, 3, 5, 4, 6, 5, 8, 7, 6, 7, 6, 7, 6, 7, 6, 7, 5, 7, 0, 1];
% Define step size and range
step_size = 5;
x_steps = 0:step_size:max(X);
% Initialize output
y_steps = zeros(1, length(x_steps) - 1);
% Loop through each step and calculate the mean of y values
for i = 1:length(x_steps)-1
% Find indices of X within the current step range
indices = X >= x_steps(i) & X < x_steps(i+1);
% Calculate the mean of corresponding y values
if any(indices)
y_steps(i) = mean(y(indices));
else
y_steps(i) = NaN; % Assign NaN if no values fall in the range
end
end
% Display the result
disp('Discrete Steps:');
disp(x_steps(2:end)); % Display step points (skip the first, 0)
disp('Mean Values:');
disp(y_steps);
Output
For both MATLAB and Python, the output will look something like this:
Discrete Steps (x):
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70]
Mean Values (y):
[3, 5, 5, 8, 7, 6, 6.5, 7, 6, 7, 6, 7, 6, 0.5]
Explanation
- Defining Steps:
- Define discrete steps (
x_steps) with the desired step size (5in this case).
- Define discrete steps (
- Finding Indices:
- For each step interval, identify the indices of XX that fall within the range [xi,xi+1)[x_i, x_{i+1}).
- Computing Mean:
- Use the indices to calculate the mean of corresponding yy-values within each step range.
- Handling Missing Data:
- If no XX-values fall into a particular step range, assign
NaN.
- If no XX-values fall into a particular step range, assign
This approach is efficient, avoids manual computation, and works for datasets of any size.
Have a different question? Ask here