PDA

View Full Version : help with matlab


cyrusmekon
2006-04-12, 02:33
Ok so i have this assignment which is doing my head in.

I am trying to do the following

x=(-4*pi:2*pi)
y=((x^2)-1)*cot(x)
plot(x,y)

but i get this error

Error in ==> Untitled4 at 2
y=((x^2)-1)*cot(x)

Can anyone help, all my lecturers have gone home and google doesnt seem to help!!

Thank you im a noob.

bassplayinMacFiend
2006-04-12, 07:10
Maybe cot (cotangent?) is identified by arctan or tan-1? I know nothing of Matlab, but you may need to change the cotangent part of your function.

Try using (1/tan(x)) or (cos(x)/sin(x)), maybe that'll work?
This page shows the math. (http://www.mathwords.com/c/cotangent.htm)

[edit]
I found this matlab cotangent page. (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/cot.html)

[edit 2]
You may have a syntax error in your definition of x in the first line. I know nothing of matlab though, just going on the example they give on the matlab page in my first edit.

ShadowOfGed
2006-04-12, 10:47
x=(-4*pi:2*pi)
y=((x^2)-1)*cot(x)
plot(x,y)Alright, here are my comments.

When creating arrays like x, you do not need the surrounding parenthesis. Those are what are causing your errors, I suspect. Lists, arrays, and matricies are delimited using square brackets, [ ], in MATLAB.

Also, when specifying ranges, particularly non-integer regions, you probably want to include the optional middle parameter that lets you specify the interval between consecutive elements. The default interval is 1, which is going to yield a very coarse graph. What you probably want is something closer to 0.1 or 0.01 as your interval, to get a better graph.

Then, you're going to run into trouble in your assignment for y. Recall that MATLAB stands for MATrix LABoratory. Thus, all operations, by default, are matrix operations. In this setting, you DO NOT want matrix multiplication and exponentiation. Most operations can be converted to element-wise operations by prefixing the operator with a period. For example, A * B computes the product of the matrices A and B, whereas A .* B multiplies each element of A by the corresponding element in B, and requires that A and B have the same dimensions.

With all that said, the code you probably want is something like this:x = -4*pi:0.05:4*pi;
y = ((x .^ 2) - 1) .* cot(x);
plot(x,y)
I added the semicolons to suppress the excessive output MATLAB generates when assigning matrices.

NOTE: I tried plotting this in my copy of MATLAB and got nothing meaningful. Turns out that this is because sin(4*pi) is zero, so the function evaluates to an enormous value at cot(4*pi). It's not undefined because MATLAB uses digitized numbers instead of the exact value of the irrational number Pi, but it does get huge. You can avoid this by slightly adjusting your ranges for x. For example, start at -4*pi+0.01. Play around a bit and see what yields a decent graph.

Hope this helps!