MATLAB: Return values from nested if statement in function

for loopfunctionif statementvector

I'm trying to write a function that will take in the vectors date, pH and depth, the minimum and the maximum depth. It will return new date and pH vectors that only contain the data when the depth was >= the minimum or < the maximum. I've tried a few variations of the code, but everything either doesn't give a result or throws an error. Below is my most recent attempt, but it is only returning the empty vector, which isn't correct. The pH, date and pressure_dbar (which is the depth) variables were imported from a .mat file and work properly. Any tips on why this isn't working properly would be appreciated.
minimum = min(pressure_dbar);
maximum = max(pressure_dbar);
function [newDate, newpH] = oceanpHdepth(date, pH, pressure_dbar, minimum, maximum)
for i = 1:length(date)
for j = 1:length(pH)
if (pressure_dbar >= minimum)
if (pressure_dbar < maximum)
newDate = date(i);
newpH = pH(j);
end
end
end
end
end

Best Answer

Using loops is a very inefficient way to perform this task: MATLAB is most efficient when operating on complete arrays, for example using vectorized operations or matrix indexing. So it is much better to simply generate the indices once, and then apply them to the complete input vectors, like this:
function [newDate, newpH] = oceanpHdepth(date, pH, pressure_dbar, mnv, mxv)
idx = pressure_dbar >= mnv & pressure_dbar < mxv;
newDate = date(idx);
newpH = pH(idx);
end
PS: the vector idx is called a "logical index", you can read about it here: