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

2 views (last 30 days)
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);
If anyone can point me in the right direction it would be a huge help, thank you!

Sign in to comment.

Answers (2)

Rajani Mishra
Rajani Mishra on 9 Sep 2019
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));
z = z + x(n)*y(1) -x(1)*y(n);

Alex Mcaulley
Alex Mcaulley on 9 Sep 2019
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!