MATLAB TUTORIAL - PART VIII
Polynomials in MATLAB are defined according to there coefficients, for example:
f (x) = 5x^4 + 10x^2 + 2x + 7 is defined as :
A=[5 0 10 2 7];
Notice the “0” is added to account 0x^3
To compute the roots of A, type:
>> roots(A)
ans =
0.3323 + 1.1880i
0.3323 - 1.1880i
-0.3323 + 0.8997i
-0.3323 - 0.8997i
To evaluate A at x=3 :
>> polyval(A,3)
ans =
508
Also MATLAB supports symbols and below is a description on how to define symbols and how to do some operations using these symbols.
- Define a symbolic variable x:
>> x=sym(’x')
x =
x
- Integrate the following function from t=0 to t=2000:
>> int(1/sqrt(12*x+0.02*x^2),0,2000)
ans =
-5/2*2^(1/2)*log(2)+5*2^(1/2)*log(23*2^(1/2)+4*65^(1/2))-5*2^(1/2)*log(3)
- Get a numeric evaluation of your answer:
>> eval(ans)
ans =
19.2740
Instead of inserting the commands one by one on command prompt we can directly write them in form of a code in an M-file.
- Open an M-File in MATLAB: File->New->M-File
- Type the following into the M-File and run it in order to see the plots:
clear all %Clear all the variables
clc %clear command prompt
time=0:0.01:10; %define the time
A=cos(2*time); %define function A
B=time.*sin(2*time); %define function B
figure (1) %Open a new Figure and number it as: 1
plot(time,A) %Plot function A
xlabel(’Time’) %add a label for the x axis
ylabel(’Function A’) %add a label for the y axis
figure (2) %Open a new Figure and number it as: 2
plot(time,B) %Plot function A
xlabel(’Time’)
ylabel(’Function B’)
And run the code by pressing F5.
Notice that MATLAB will prompt you to save the M-file. Assign a name for the file, and when prompted to change the working directory type “Ok.
Of course you can use the subplot command in order to show several graphs on one figure but I will leave this for you to discover. And you can make the graph clearer when plotting several curves on the same graph using the ‘hold on’ by writing the legends but the legend command. And a good title for the graph too is also nice using the title command.
The final thing that we will cover is the use of functions.
As we have seen earlier, we have used an M-file to run a script, but we can also use it as a function by adding the following on top of the M-file:
function [out1, out2, ...] = funname(in1,in2, …)
where this function has funname as its name with arguments in1,in2,…
and it returns out1,out2,…
If we want to call this function from another file, all what we have to do is to write
[A B ...]=funname(in1,in2,….) where we put a value for in1,in2,….
We should also note that fucntion make use of their own local variables.
In case of any confusion, MATLAB help is really a good source to solve your problem.
And also you can visit MATLAB central where you can find lots of interesting stuff there.
This is the end of this tutorial.
I hope you enjoyed it!!
Filed under: MATLAB

Leave a Reply
You must be logged in to post a comment.