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

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'.

 採用された回答

Cam Salzberger
Cam Salzberger 2017 年 8 月 31 日
編集済み: Cam Salzberger 2017 年 8 月 31 日
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 件のコメント

mark dodds
mark dodds 2017 年 8 月 31 日
Thank you so much Cam Salzberger. It works flawless now. Could the problem be solved using loops? Or was I completely offtrack? Thanks again! -Mark
No, you absolutely could use loops, it just wouldn't be very efficient. The issue is that you'd either have to define a second vector larger than you need, or build the vector as you go without preallocation.
If you wanted to do loops without running into the preallocation issue, it'd probably make sense to not bother building a second vector at all, and just process the values on the fly:
total = 0;
count = 0;
for k = numel(r)
if r(k) > l && r(k) < u
total = total + r(k);
count = count + 1;
end
end
averageRate = total/count;
Ah, okay that makes sense! Thanks a lot Cam!
for k = 1: numel(r)
Cam Salzberger
Cam Salzberger 2017 年 9 月 3 日
Oops, yeah, my bad. Thanks for catching that.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeProgramming についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by