Clear Filters
Clear Filters

Extracting values from an array corresponding to the indices of certain values from another array.

7 views (last 30 days)
I have an array of angle values (Angle) and I need to collect the angle values from the start to the end with intervals of 5 degrees with their indices so that I can collect the corresponding Torque values from a second array that corresponds to the found indices. The data is derrived from a servomotor that does not use a fixed sample frequency.
So far I have the following, but I think that 'find' does not allow negative integers:
deltaA = 5;
nsteps = floor( (Angle(end) - Angle(1)) /deltaA );
stepAngle = [Angle(1,1)+[0:nsteps]*5, Angle(end)]';
i = find(Angle, stepAngle)
Maybe there is a simpler solution, I hope someone can help.
  1 Comment
Guido
Guido on 17 Jan 2024
I have found a solution allready, hopefully this can help others with the same problem, a simpler solution is still allways welcome.
deltaA = 5;
nsteps = floor( (Angle(end) - Angle(1)) /deltaA );
stepAngle = [Angle(1)+[0:nsteps]*5, Angle(end)]';
for k = 1:length(stepAngle)
[val,idx]=min(abs(Angle-stepAngle(k)));
index(k) = idx;
end
stepTorque = Torque(index)

Sign in to comment.

Accepted Answer

Jon
Jon on 17 Jan 2024
I would suggest using MATLAB's interp1 function for this purpose, as illustrated below. Note you can resample using the nearest points as you show, or I think preferably using linear interpolation to calculate the torque values at the new sample points. Both approaches are shown below, the only difference is the method argument for interp1
% create example data set with unequally spaced samples
startAngle = 0;
endAngle = 270;
numSamples = 40;
delta = rand(numSamples,1);
angle = cumsum(delta)/sum(delta)*(endAngle -startAngle);
torque = sind(angle);
% find torque at equally spaced intervals, using nearest
% point
stepAngle = startAngle:5:endAngle;
stepTorque = interp1(angle,torque,stepAngle,"nearest");
% plot results
figure
plot(angle,torque,'-*',stepAngle,stepTorque,'-o')
legend('original points','equally spaced')
title('Resample using nearest points')
% find torque at equally spaced intervals using linear interpolation
stepAngle = startAngle:5:endAngle;
stepTorque = interp1(angle,torque,stepAngle,"linear");
% plot results
figure
plot(angle,torque,'-*',stepAngle,stepTorque,'-o')
legend('original points','equally spaced')
title('Resample using linear interpolation')

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!