필터 지우기
필터 지우기

Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

what correction is required in the code?

조회 수: 2 (최근 30일)
Manav Divekar
Manav Divekar 2021년 11월 11일
마감: Cris LaPierre 2021년 11월 11일
I am trying to perform 2*2 + 2*5 + 5*8, for [2 2 5 8] vector which is product of consicutive and sum of all. without using sum() & diff() and using for loop
function [out] = pairprodsum (m)
s = 0
for i = 1
b = m(1:end-1).*m(2:end);
s = s + b;
end
out = s;

답변 (2개)

James Tursa
James Tursa 2021년 11월 11일
If the homework assignment specifies you must use a loop, then I don't think the intent was for you to wrap a simple i=1 range around vectorized code. That being said, I suppose your "loop" technically qualifies.
b is a vector. You simply need to sum all the elements of b and return that. s = s + b does not sum the element of b ... it simply creates a new vector s that is a copy of b. You need different code to sum the elements of b. There are various ways to do this, which I will let you figure out.
  댓글 수: 4
Manav Divekar
Manav Divekar 2021년 11월 11일
its just gives sum of only first postion of the arrey.
James Tursa
James Tursa 2021년 11월 11일
How could you maybe change the for loop range so it added up all of the elements?

Jan
Jan 2021년 11월 11일
편집: Jan 2021년 11월 11일
A hint: You want to perform this:
  • s = 0
  • s = s + 2*2
  • s = s + 2*5
  • s = s + 5*8
You need to loop over the indices of m. There is 1 iteration less than the number of elements of m.

이 질문은 마감되었습니다.

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by