MATLAB: Findpeaks in for loop; find maximum’s corresponding x value

findpeaks;loop;function;maximum

Hi, I want to find in each loop for L, the maximum value of SP and corresponding p value. That means, I want the results to be two vectors of length numel(L).
I know that findpeaks could help to identify the maximum and its location, but i always got the error message "In an assignment A(:) = B, the number of elements in A and B must be the same. Error in optimalp(j) = prange(locs);"
Could anyone help me to fix this? Or is there any other methods to output the maximum of SP and corresponding p values? Because i want to use the vectors to plot the graph later.
THANKS!!!
L = 0.01:0.01:1;
p = 0:0.01:1;
optimalp = zeros(1,numel(L));
maximum = zeros(1,numel(L));
SP = zeros(1,numel(p));
for j = 1:numel(L)
for i = 1:numel(p)
if Lambda(j) >= mu
if p(i) < R-c^2/(mu*phi)
SP(i) = p(i)*(mu-c/(R-p(i)));
else
SP(i) = p(i)*(mu-sqrt(mu*phi/(R-p(i))));
end
else
SP(i) = p(i)*L(j);
end
end
[pks,locs]=findpeaks(SP);
optimalp(j) = p(locs);
end

Best Answer

findpeaks returns all the peaks it finds by default. if you just want the largest one you can change your call to:
[~, lochighest] = findpeaks(SP, 'SortStr', 'descend', 'NPeaks', 1);
optimal(j) = p(lochighest);