Add and subtract matrix element consecutively

조회 수: 2 (최근 30일)
Hoang Trung Le
Hoang Trung Le 2022년 8월 8일
댓글: Dyuman Joshi 2022년 8월 8일
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;
a = 1×10
1 2 3 4 5 6 7 8 9 10
temp_sum = 0;
for i = 1:10
sum_a = temp_sum + (-1)^i*a(i);
temp_sum = sum_a;
end
temp_sum
temp_sum = 5
I wonder if there is other more elegant way to solve this problem. Thanks!

채택된 답변

Rik
Rik 2022년 8월 8일
Since you already solved your own homework, I see no problem in providing you with some code.
The main thing to remember is that a vectorized solution is faster than a loop (if a direct function exists).
A=zeros(200,1000);
tic
A1=A;
for n=1:numel(A),A1(n)=A1(n)+1;end
toc
Elapsed time is 0.007344 seconds.
tic
A2=A;
A2=A2+ones(size(A2));
toc
Elapsed time is 0.003079 seconds.
% Or even better in this case: A3=A3+1;
You need to find a way to generate the full array efficiently.
You already saw you can use (-1)^n to alternate positive and negative factors. How would you write such an expression to generate the vector you need?
% This is a tricky step that may be hard to debug: you need .* for
% element-wise multiplication
[1 2 3 4].*[1 -1 1 -1]
ans = 1×4
1 -2 3 -4
Now, how would you sum these elements?

추가 답변 (1개)

Dyuman Joshi
Dyuman Joshi 2022년 8월 8일
편집: Dyuman Joshi 2022년 8월 8일
What you are doing in a loop, can be done via element-wise multiplication as well.
You can make an array for the corresponding powers of -1, multiply it with a and sum it.
a = 1:10;
%using sum
sum(a.*(-1).^a)
ans = 5
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
a = 1×10
1 2 3 4 5 6 7 8 9 10
(-1).^a'
ans = 10×1
-1 1 -1 1 -1 1 -1 1 -1 1
a*(-1).^a'
ans = 5
  댓글 수: 2
Rik
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
Dyuman Joshi 2022년 8월 8일
You are right, RIk, I should have done that initially.
I have edited my answer now.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by