Create a new array by summing the columns of old array

8 ビュー (過去 30 日間)
Shanice Kelly
Shanice Kelly 2021 年 1 月 5 日
回答済み: Michael 2021 年 1 月 5 日
I have an array that is 512x64, I would like to sum each consecutive columns until I have a new array that is 512x32,
so old_array column 1 + old_array column 2 = new_ array column 1
old_array column 3 + old_array column 4 = new_ array column 2
old_array column 5 + old_array column 6 = new_ array column 3
etc.
I have tried using a nested for loop but I am unsure what to exceute inside. Thank you for any help!

採用された回答

Stephen23
Stephen23 2021 年 1 月 5 日
編集済み: Stephen23 2021 年 1 月 5 日
The MATLAB approach, where M is your matrix:
new = M(:,1:2:end) + M(:,2:2:end);

その他の回答 (3 件)

Walter Roberson
Walter Roberson 2021 年 1 月 5 日
reshape( sum( reshape(YourArray, 512, 2, 32), 2), 512, 32)

Daniel Catton
Daniel Catton 2021 年 1 月 5 日
a = YourArray;
b = [];
for i = 1:2:32
b = [b a(:,i)+a(:,i+1)];
end

Michael
Michael 2021 年 1 月 5 日
By calling up the matrix elements using their linear indices and skipping by the number of rows in your matrix you can do what you are trying. I have a simple example below using a 2x10 matrix that produces a 2x5 result. Note that this isn't the most efficient method, as it does some summations that aren't necessary and just throws them away in the last line of code. Unless you are worried about speed or memory, this is probably just fine though. I hope this helps.
%Build the matrix
blah = [1 2 3 4 5 6 7 8;...
9 10 11 12 13 14 15 16];
%Get sizes
[rows,cols] = size(blah);
els = numel(blah);
%Create an list of the linear indices of blah that excludes the last column
allbutlastcol = 1:(els-rows);
%Do the summation, but get the result as a vector
%(Here is where we skip with the +rows)
blahsum_vector = blah(allbutlastcol)+blah((allbutlastcol)+rows);
%Reshape the result to get the matrix result
blahsum_matrix = reshape(blahsum_vector,rows,cols-1);
%Remove the columns we don't need
result = blahsum_matrix(:,1:2:end)
result =
3 7 11 15
19 23 27 31

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by