How can I loop though a vector select certain elements and store them in a new vector?
7 views (last 30 days)
Show older comments
mark dodds
on 31 Aug 2017
Commented: Cam Salzberger
on 3 Sep 2017
I want to have a function that calculates the average of an input vector that satisfies certain conditions. Here is how I imagine my algorithm:
- user inputs a vector ,r, and 2 scalars,u and l (upperbound and lowerbound)
- script loops though r and evaluates each expression.
- If u>r<l then select value and add to a new vector, v. (vectorize?)
- Final output should be average=sum(v)/size(v)
My code so far:
function averageRate = fermentationRate(r, l, u)
[row, col]=size(r); %dimensions of inputvec,r
for i=1:col %iterates through 1 to last column in the inputvec,r
if r>l && r<u %condtions that must be true before value can be used
v=0+(r);
[row1,col1]=size(v) %dimension of vector,v containing useable inputs
averageRate=sum(v)/col1; %average of inputs
end
end
end
Error in Fermenationproblem (line 8)
[row, col]=size(r); %dimensions of inputvec,r
>> averageRate([20.1 19.3 1.1 18.2 19.7 121.1 20.3 20.0], 15,25)
Undefined function or variable 'averageRate'.
0 Comments
Accepted Answer
Cam Salzberger
on 31 Aug 2017
Edited: Cam Salzberger
on 31 Aug 2017
Hey Mark,
There is a very convenient feature in MATLAB called logical indexing. This can allow you to vectorize your code, and drastically improve efficiency. There is also the built-in mean function to determine average, rather than doing sum/count.
% Figure out which vector elements are within bounds
% Needs to use element-wise &, not logical &&
idx = r > l & r < u;
% Determine average:
averageRate = mean(r(idx));
Also, I'd recommend not using i, j, or l for variable names. i and j have built-in meanings in MATLAB (imaginary number), and l looks too much like 1.
-Cam
4 Comments
More Answers (0)
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!