フィルターのクリア

How to apply the same operation to an ever increasing number of columns?

2 ビュー (過去 30 日間)
Zulfiqar Alibhai
Zulfiqar Alibhai 2023 年 11 月 9 日
コメント済み: William Rose 2023 年 11 月 9 日
lets say you have an array called A = (1:7) and a matrix called B = (1:20,1:7)
A
B
if I want to multiply each row from B with a value from A and than sum each row, it's: sum(A.*B')
R_7
If I want to do a specific row, it's: (A(2).*B(1:20,2))
if I want to do the first 5 rows, it's: sum(A(1:5).*B(1:20,1:5))
But what I want to do is to create a new matrix where each row is the sum of one more colum then the last.
Basically, it would look like this:
C
How would I go about doing that?

採用された回答

Dyuman Joshi
Dyuman Joshi 2023 年 11 月 9 日
C = cumsum(A.*B, 2)

その他の回答 (2 件)

Onesimus Hewett
Onesimus Hewett 2023 年 11 月 9 日
The easiest method is to use a for loop.
C = zeros(20, 7);
for i = 1:7
C(:, i) = B(:, 1:i)*A(1:i)';
end
C

William Rose
William Rose 2023 年 11 月 9 日
[I moved my suggestion from comment section to answer section.]
a=[1:7]; b=zeros(20,7); c=b;
for j=1:7, b(:,j)=10*[1:20]'+j; end
disp(b(1:3,:))
11 12 13 14 15 16 17 21 22 23 24 25 26 27 31 32 33 34 35 36 37
for j=1:7
for i=1:j
c(:,j)=c(:,j)+b(:,i)*a(i);
end
end
disp(c(1:3,1:3))
11 35 74 21 65 134 31 95 194
I think this is working. Check it.
  2 件のコメント
William Rose
William Rose 2023 年 11 月 9 日
The answer from @Onesimus Hewett is more elegant than mine.
William Rose
William Rose 2023 年 11 月 9 日
And so is @Dyuman Joshi's.

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

カテゴリ

Help Center および File ExchangeData Type Identification についてさらに検索

タグ

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by