Some Matlab Basics and Extensions To (Potentially) More Useful Stuff
Some Matlab Basics and Extensions To (Potentially) More Useful Stuff
useful stuff
1. Matlab basics
Type
Comment
a=5*6;
disp(a)
help disp
B=5/4;
B
b=a^B
whos
clc
this clears the screen, but leaves all the variables in the workspace.
clear a
whos
clear
whos
clc
Comment
x=2; sin(x)
x=30; sin(pi*x/180)
if we wanted to plot sin(x) 0<x<2 we could create a number of points individually and plot
each point, or we could create a small m-file with a loop. However matlab has a very much
easier way to make a list of numbers (vector).
x=0:0.1:2*pi;
x(1)
x(2)
displays the 2
x(end)
nd
value of x
x(length(x))
y=sin(x);
the sin and most matlab functions can accept vectors and
matrices as arguments not just single numbers.
plot(x,y)
help plot
plot(x,cos(x),'ro',x,sin(x),'g+')
figure; plot(x,cos(x).*sin(2*x))
help whitebg
whitebg
whitebg
close all
clear; clc
3. Matrices and simultaneous equations
Matrices are easy to deal with in Matlab (which is short for Matrix Laboratory).
A=rand(4)
B=zeros(4,6)
C=ones(2,8)
D=eye(5)
A
nd
st
A(1,2)
A(4,1)
A(3,2)=10
whos
size(A)
x=1:5;
x^2
tries to find the square of x you will get an error message saying
st
th
x*x
error message
x.*x
this works
x./x
A^2
A.^2
Simultaneous equations
x+y=3
2x + y = 5
1 1 x 3
=
2 1 y 5
A X = B
would like to be able to write X =
B=[3;5]
note to enter a matrix by hand enter each row with the numbers
A=[1 1;2 1]
X=A\B
B=rand(8,1)
A=rand(8)
X=A\B
clear; clc
N-1
+ + P(N) X + P(N+1)
So for example y = 4x + 2x + 5x 7
P=[4 2 5 -7];
X=-10:0.01:10;
Y=polyval(P,X);
calls the matlab function polyval, which is why P must take the
form above, otherwise function will not work.
plot(X,Y)
Note find out for yourself about polyfit a matlab function for fitting polynomials
p=[1 -6 11 -6];
r=roots(p)
y=polyval(p,r)
Method 1: at the command line, time them in one at a time, if you make a mistake you kinda
have to start again.
A=2;
B=3;
t = linspace (0, 2*pi, 200);
x = A*cos(t);
y = B*sin(t);
plot(x,y,r)
axis equal
Makes the axis the same size (so a circle will look like a circle)
xlabel(x)
ylabel(y)
title(ellipse)
So x, y will be the outputs from this function fplot_ellipse and A, B are the input arguments.
Now from line 4 add the following note the similarity to what we have already done.
note DO NOT use clear in a function file otherwise you clear the input arguments!
Now to run this function you have some choices you can either type something like below at
the command line in matlab
>> fplot_ellipse(2,3);
Or if we were trying to be a little more clever write a script file to do this and some other bits
and bobs as below