MATLAB Answers

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

조회 수: 12(최근 30일)
SnooSquare
SnooSquare 2 Sep 2019
답변: Alex Mcaulley 9 Sep 2019
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 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 )
Alex Mcaulley
Alex Mcaulley 2 Sep 2019
As an alternative of Adam's suggestion, see circshift

로그인 to comment.

답변(2개)

Rajani Mishra
Rajani Mishra 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);

  댓글 수: 0

로그인 to comment.


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

  댓글 수: 0

로그인 to comment.

이 질문에 답변하려면 로그인을(를) 수행하십시오.

태그


Translated by