How to apply the same operation to an ever increasing number of columns?
조회 수: 2 (최근 30일)
이전 댓글 표시
lets say you have an array called A = (1:7) and a matrix called B = (1:20,1:7)
![A](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1534267/A.png)
![B](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1534272/B.png)
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](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1534277/R_7.png)
If I want to do a specific row, it's: (A(2).*B(1:20,2))
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1534282/image.png)
if I want to do the first 5 rows, it's: sum(A(1:5).*B(1:20,1:5))
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1534287/image.png)
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](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1534292/C.png)
How would I go about doing that?
댓글 수: 0
채택된 답변
추가 답변 (2개)
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
댓글 수: 0
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,:))
for j=1:7
for i=1:j
c(:,j)=c(:,j)+b(:,i)*a(i);
end
end
disp(c(1:3,1:3))
I think this is working. Check it.
댓글 수: 2
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Identification에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!