How can I return the minimum value that is not zero inside a for loop?

2 ビュー (過去 30 日間)
Thomas
Thomas 2016 年 2 月 12 日
編集済み: Fangjun Jiang 2016 年 2 月 12 日
Hi,
I have a for loop that find the min, max and mean of a set of data for each month that is entered and I want the minimum function to return the minimum value that is not zero. I know if i have matrix A i can use,
min(A(A>0);
But in this loop it does not allow me to do this, here is the code I am using,
for i = unique(months)' %allows function to work with any number of months
maxs(i,:) = max(hourdata(months==i,1:end));
mins(i,:) = min(hourdata(months==i,1:end));
means(i,:) = mean(hourdata(months==i,1:end));
end
I tried using the following for the minimum value but it does not like it,
mins(i,:) = min(hourdata(hourdata>0(months==i,1:end)));
I get the error 'Unbalanced or unexpected parenthesis or bracket'.
Any help would be greatly appreciated.

回答 (1 件)

Fangjun Jiang
Fangjun Jiang 2016 年 2 月 12 日
編集済み: Fangjun Jiang 2016 年 2 月 12 日
How about using a temp variable?
temp=hourdata(months==i,1:end);
temp(temp<=0)=inf;
mins(i,:) = min(temp,[],1);
clear temp
  2 件のコメント
Thomas
Thomas 2016 年 2 月 12 日
The result I am expecting is a 12x24 double (12 months of the year and over 24 hours) and using the temp variable gives a 12x1 double. This might be because that is where the only values greater than zero are. However, I tried with,
if true
temp = hourdata(months==i,1:end);
mins(i,:) = min(temp(temp>=0));
clear temp
This rendered the same result of a 12x1 double.
Fangjun Jiang
Fangjun Jiang 2016 年 2 月 12 日
編集済み: Fangjun Jiang 2016 年 2 月 12 日
I see. To keep the matrix formation, you can temporarily replace those zero and negative values with a very large number and then do the min() operation.
I also see a potential problem when a particular month has only one row of data. In that case, the statement inside the for-loop will return a 1x1 scalar, rather than a 1x24 vector which is desired. So please use the optional input argument of min() function.
See if the update code works.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by