How can I loop though a vector select certain elements and store them in a new vector?

7 vues (au cours des 30 derniers jours)
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:
  1. user inputs a vector ,r, and 2 scalars,u and l (upperbound and lowerbound)
  2. script loops though r and evaluates each expression.
  3. If u>r<l then select value and add to a new vector, v. (vectorize?)
  4. 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'.

Réponse acceptée

Cam Salzberger
Cam Salzberger le 31 Août 2017
Modifié(e) : Cam Salzberger le 31 Août 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 commentaires
mark dodds
mark dodds le 1 Sep 2017
Ah, okay that makes sense! Thanks a lot Cam!
for k = 1: numel(r)
Cam Salzberger
Cam Salzberger le 3 Sep 2017
Oops, yeah, my bad. Thanks for catching that.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by