MATLAB: Extract maximum values from two different vectors when their associated location vectors crosses

findindexindexingloopMATLABvectorvectorization

Dear all,
I have four vectors, two with peak values and two vectors with associated location values based on two peak analysis.
loc1=[10.4 15.8 29.2 32.1 35.9];
loc2=[10.1 15.2 35.6];
pks1=[10 1 5 4 100];
pks2=[8 5 1000];
I want create a new vector with the maximum value from vector pks1 and from pks2 when loc1 and loc2 have the approximately same value (~+-2).
I.e. loc1 and loc2 cross at position 1,2 and 5 (10.1 and 10.4, 15.2 and 15.8, 35.6 and 35.9), so my new vector will be: final=[10 5 5 4 1000].
Can anyone help me out?
Thanks in advance!

Best Answer

"I need to account for all peaks in pks1, but also considered that the maximum peak force may occur in the second sensor (pks2)"
Just a small adjustment is needed in the code from my comment under your question.
loc1=[10.4 15.8 29.2 32.1 35.9];
loc2=[10.1 15.2 35.6];
pks1=[10 1 5 4 100];
pks2=[8 5 1000];
% Find indices of loc1 & loc2 that are within 2 units of each other
% locsAreClose(n,m) determines if loc1(n) and loc2(m) are within +/-2
locsAreClose = abs(loc1(:)-loc2(:).')<=2; %rows@loc1, cols@roc2
% Find the max between all pks pairs

maxPairs = max(pks1(:),pks2(:).');
% Output

pksMax = pks1;
pksMax(any(locsAreClose,2)) = maxPairs(locsAreClose);
[update]
For n peak/loc vectors, just combine the vectors except for loc1 and pks1. So, this can work for any number of loc/pks vectors.
loc1=[10.4 15.8 29.2 32.1 35.9];
loc2=[10.1 15.2 35.6];
loc3=[15.3 29 35.6 44];
pks1=[10 1 5 4 100];
pks2=[8 5 1000];
pks3=[7 6 50 90];
loc23 = [loc2, loc3]; % combine them into 1 vector

pks23 = [pks2, pks3]; % combine them into 1 vector
% Find indices of loc1 & loc23 that are within 2 units of each other
locsAreClose = abs(loc1(:)-loc23(:).')<=2; %rows@loc1, cols@loc23
% Find the max between all pks pairs
maxPairs = max(pks1(:),pks23(:).');
maxPairs(~locsAreClose) = -inf;
maxVals = max(maxPairs,[],2); % a vector of all max values
% Output
pksMax = pks1;
pksMax(any(locsAreClose,2)) = maxVals(any(locsAreClose,2));