MATLAB: Function to fill an array given conditions.

#dynamicarrayfunction

Hi All,
I am trying to write a function to fill an array given conditions. basiclly the user inputs two variables a max and min and given these
values it creates two new row vectors, ph and date, which is a subset of an orignal vector.
My code is given below –
function [datenew,phnew] = subsetdata(date, ph, pressure, min, max)
%create empty array
datenew=cell(1,5000);
phnew=cell(1,5000);
%loop through each point
for i=1:size(pressure)
%check condition
if (pressure(i,:)>=min & pressure(i,:)<max)
%fill array if condition met
datenew{i}=date(i);
phnew{i}=ph(i);
end
end
end

Best Answer

validIdx = pressure >= minVal & pressure < maxVal;
datenew = date( validIdx );
phnew = ph( validIdx );
should do this for you without needing the loop and using logical indexing instead. I don't know why you are putting results in a cell array though. Never use a cell array when a numeric array will do the job.