How do I code a function that's supposed to be an infinite pattern?

조회 수: 1 (최근 30일)
SnooSquare
SnooSquare 2019년 9월 2일
답변: Alex Mcaulley 2019년 9월 9일
I have a question as follows,
Let x = [x1 x2 x3 x4…..xn] and y = [y1 y2 y3 y4…….yn]. Write a MATLAB function to determine the following: (x1y2-x2y1+x2y3-x3y2+…..xny1-x1yn) Now assume x = [1 2 3 4 5] and y = [10 20 30 40 50]. Evaluate the above in this case.
However, I don't know how to code for a function that has "....yn" or "...xn",
What I have right now is literally this,
function [z] = Assignment1Question6b(x,y)
z = x(1)*y(2)-x(2)*y(1)+x(2)*y(3)-x(3)*y(2)+x(3)*y(4)-x(4)*y(3) + x(5)*y(1)-x(1)*y(5);
end
If anyone can point me in the right direction it would be a huge help, thank you!
  댓글 수: 2
Adam
Adam 2019년 9월 2일
편집: Adam 2019년 9월 2일
You can use a for loop, over the size of the input array, since the formula is clearly defined in terms of e.g. k and k + 1 for a value k. Mind you, the leap from the ... to the final set of terms is a little suspicious since the last term apparently wraps round to work with index 1 when k + 1 would become great than n. It's still well defined, but not as clearly as it might be to be truly rigorous.
Remember that while the formula may be theoretically infinite the array passed in will always have a finite size, n, which you can get using, for example, numel( x )
Alex Mcaulley
Alex Mcaulley 2019년 9월 2일
As an alternative of Adam's suggestion, see circshift

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

답변 (2개)

Rajani Mishra
Rajani Mishra 2019년 9월 9일
As mentioned in the comment by Adam, Formula may be theoretically for infinite pattern but for arrays ‘x’ and ‘y’ size will be finite and can be found out using numel(x).
For mentioned pattern you can try below mentioned code:
z = 0;
n = numel(x);
for i=1:n-1
z = z + (x(i)*y(i+1) - x(i+1)*y(i));
end
z = z + x(n)*y(1) -x(1)*y(n);

Alex Mcaulley
Alex Mcaulley 2019년 9월 9일
Another possibility:
res = sum(x.*circshift(y,-1) - y.*circshift(x,-1))

태그

Community Treasure Hunt

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

Start Hunting!

Translated by