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

1 view (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);
end
If anyone can point me in the right direction it would be a huge help, thank you!
  2 Comments
Adam
Adam on 2 Sep 2019
Edited: Adam on 2 Sep 2019
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 )

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));
end
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))

Tags

Community Treasure Hunt

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

Start Hunting!