How to obtain length of number of columns which has data

31 ビュー (過去 30 日間)
Damith
Damith 2015 年 3 月 25 日
コメント済み: dpb 2015 年 3 月 26 日
Hi,
I need to loop though the columns in " mTot " and select the columns which has data (for example column 1 and 2).
If I do
length(mTot)
ans
51681
But, I need to obtain the answer as 2 (becuase only column 1 and 2 has data). Can somebody suggest me a method?
Thanks in advance.
  4 件のコメント
James Tursa
James Tursa 2015 年 3 月 25 日
sum(~all( mTot == 0, 1 )) ?
dpb
dpb 2015 年 3 月 25 日
See below; looping sometimes is the right answer. How have you ensured there's nothing past the first N months and it's not the missing values problem we were discussing in the original thread? Simply iterate over the columns and test for each; if you have somehow got it where they are all contiguous then after the first false result use break to terminate the loop.

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

採用された回答

Image Analyst
Image Analyst 2015 年 3 月 25 日
Sum the columns and look for zero
columnSums = sum(mTot, 1);
% Find column numbers that are not all zeros
colIndexesWithData = find(columnsSums ~= 0);
This can even handle columns with zeros in between other columns, in case that ever happens.
If you want to find the very last column that has data in it, get the last element.
lastColWithData = colIndexesWithData (end);
  2 件のコメント
Image Analyst
Image Analyst 2015 年 3 月 25 日
By the way, length is the max of the two dimensions, i.e. the larger of the number of rows or the number of columns.
Damith
Damith 2015 年 3 月 25 日
Thanks.

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

その他の回答 (1 件)

dpb
dpb 2015 年 3 月 25 日
IA has the right idea but coming in from the cold doesn't know the full picture... :)
As I pointed out in the discussion accompanying the code that I wrote from whence the above comes, the NaN initialization option gives you the columns that are missing data or it's simply remove the zero columns from the array (albeit you do need to keep track of which is which since the columns represent month of year and if there's a case where there's a missing other than trailing your index otherwise will be off).
Probably the most generic thing is to simply loop over the full array and check that any(:,colIdx) is True, if so, then write that column, if False skip it. This keeps the indices and the month in synch.
  2 件のコメント
Damith
Damith 2015 年 3 月 25 日
Thanks a lot again.
dpb
dpb 2015 年 3 月 26 日
I added an additional thought on the overall process at the other thread if you're back, Damith, on how to "have your cake and eat it, too!"

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by