Add and subtract matrix element consecutively
이전 댓글 표시
My assignment asks me to add and subtract elements in a matrix consecutively and I am using a for loop to solve.
Example
a = 1:10;
temp_sum = 0;
for i = 1:10
sum_a = temp_sum + (-1)^i*a(i);
temp_sum = sum_a;
end
temp_sum
I wonder if there is other more elegant way to solve this problem. Thanks!
채택된 답변
추가 답변 (1개)
a = 1:10;
%using sum
sum(a.*(-1).^a)
Another approach is to take advantage of the fact that multiplication of a row vector and a column vector (of same number of elements, of course) will result in multiplicative sum of the two.
a - 1xn, b - nx1; a*b = a1*b1+a2*b2*+......+an*bn
%one liner
a
(-1).^a'
a*(-1).^a'
댓글 수: 2
Rik
2022년 8월 8일
Please attempt to teach the solution for homework questions, instead of just giving it.
You may also want to explain what is happening in your second solution. It will not be immediately apparent to a novice why that works or what is going on.
Dyuman Joshi
2022년 8월 8일
You are right, RIk, I should have done that initially.
I have edited my answer now.
카테고리
도움말 센터 및 File Exchange에서 Mathematics에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!