Help saving the output of a for loop within a function into a vector.

Hello. I am currently writing the below function:
function [numout, outvec]= SCAN_DATA(vectin, lowlim, uplim)
%Compares each element of vectin against lowlim and uplim and returns
%a count (numout) of how many vector elements are greater than or less than the
%limits and a vector (outvec) of the actual out-of-limit readings
for k=1:length(vectin)
if vectin(k)>lowlim && vectin(k)<uplim;
outvec=vectin(k)
numout=numel(outvec)
else outvec=0
end
end
I would like to save the data output into the vector named vectin but I only get the last output run through the loop. I am pretty new to this after looking around online, I can't figure it out. Can anyone help?

 Accepted Answer

There are vectorized ways to do this (without a loop), but to answer your question directly you could add the index numout onto your outvec "storage" line. E.g.,
numout = 0;
outvec = [];
for k=1:length(vectin)
if vectin(k)>lowlim && vectin(k)<uplim;
numout = numout + 1;
outvec(numout) = vectin(k);
end
end
This assumes the "out-of-limit" readings are the ones between the limits as you have it originally coded. If the "out-of-limit" readings are the opposite, then you need to fix the if-test.
Vectorized methods can avoid the loop, and avoid incrementally increasing the size of a variable (outvec in this case) inside a loop. E.g., you might explore what you get with these two statements and then think about how to combine them in a vector sense to get your answer directly from them:
% With no indexes used, these two expressions return vectors
vectin > lowlim
vectin < uplim

2 Comments

How are you calling the function? To get the variables in the workspace make sure you are capturing two outputs. E.g., call it like this:
[numout, outvec] = SCAN_DATA(vectin, lowlim, uplim);

Sign in to comment.

More Answers (1)

l0 = vectin>lowlim & vectin<uplim;
outvec = l0*vectin;
numout = nnz(l0);

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!