Average or sum specific-non-sequential columns

2 ビュー (過去 30 日間)
Lina Koronfel
Lina Koronfel 2021 年 9 月 8 日
コメント済み: Lina Koronfel 2021 年 9 月 9 日
Is there a straight forward quick way to do calculations (sum, mean, etc) on columns that are not in a sequence by avoiding unwanted columns?
For example, if I have 100 rows x10 columns matrix, I would like to do calculations (mean or sum) of all rows in column 1-2, 4, 6-8, and 10. I want to skip column 3,5, and 9.
The matrix of interest looks something like this: Matrix(1:100,1:10), and the columns to be skipped are in an array of their own such as this BadColumns=[3,5,9], I need help of how to avoid the bad columns by implementing the BadColumns array in the code
TheMean=mean(Matrix(:,:),2) %but avoid [3,5,9] in second dimension

採用された回答

KSSV
KSSV 2021 年 9 月 8 日
Let A be your 100x10 matrix. You can remove the said columns from he matrix and use the functions to get what you want.
idx = [3 5 9] ; % index of columns which you dont want to consider
A(:,idx) = [] ; % Remove those columns
Now A has only your required columns. You can get what you want.
  1 件のコメント
Lina Koronfel
Lina Koronfel 2021 年 9 月 8 日
Perfect Thanks alot!!

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

その他の回答 (1 件)

Image Analyst
Image Analyst 2021 年 9 月 8 日
I would have done it somewhat differently than KSSV. You don't need to change your variable - you can keep it the same, just tell mean() what columns to include in the sum:
data = randi(9, 100, 10); % Create sample data
% I have 100 rows x10 columns matrix,
% I would like to do calculations (mean or sum) of all rows in column 1-2, 4, 6-8, and 10.
% I want to skip column 3,5, and 9.
columnsToInclude = [1, 2, 4, 6:8, 10]; % Whatever you want.
theColumnMeans = mean(data(:, columnsToInclude), 1)
  1 件のコメント
Lina Koronfel
Lina Koronfel 2021 年 9 月 9 日
Thank you for the solution. In my situation I think KSSV is more straight forward because I already have the array idx of the columns to ignore. In reality it is maybe 100 out of 250 columns that need to be removed, so creating another array of columns to include maybe an extra step for me. But I'm sure this solution is more straight forward in another situation. Thanks again and cheers :)

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

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by