Using Find() in For Loop

3 views (last 30 days)
DYLAN
DYLAN on 30 Nov 2012
I am setting up a very simple matlab code to find the first value in each column of a matrix that passes a threshold value. If the matrix has a value that meets the threshold range, then it outputs an index. If the condition is not met, 'NaN' appears.The expected outcome is 1-by-5 matrix that has indice for each column.
However, I could not get IF statement to work. Each line of the code works fine but when it is put together, it does not produce the values I was expecting.
What am I missing here?
xn=[1 0 16 14 18;0 13 4 0 11; 0 4 15 1 52; 0 5 5 17 43; 0 11 5 3 14];
y=[1 24 35 15 16]; %Threshold
t=4*ones(2,5);
SD=1.5;
y_minuse_SD=y-SD*ones(1,5);
y_plus_SD=y+SD*ones(1,5);
d=1:length(xn);
for s=1:5;
if xn(d,s)<y_plus_SD(1,s) & xn(d,s)>=y_minuse_SD(1,s)
t(1,s)=find(xn(d,s)>=y_minuse_SD(1,s),1);
else
t(1,s)=NaN;
end
end

Answers (1)

Azzi Abdelmalek
Azzi Abdelmalek on 30 Nov 2012
xn=[1 0 16 14 18;0 13 4 0 11; 0 4 15 1 52; 0 5 5 17 43; 0 11 5 3 14];
y=[1 24 35 15 16]; %Threshold
[n,m]=size(xn);
SD=1.5;
y_m=y-SD;
y_p=y+SD;
z=xn(:);
out=arrayfun(@(x) find(z<y_p(x) & z>y_m(x),1),1:n,'un',0)
out(cellfun(@isempty,out))=num2cell(nan)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!