Lab1 (1)
Lab1 (1)
Matlab Basic
===================================================================
Variables
>>num_students = 9
>>lab_num = 11
>>quiz_num = lab_num
===================================================================
Operators
+ Addition
- Subtraction
* Multiplication
/ Division
^ Power
Example:
1
>> % Evaluate f(x)=x^3+2*x^2+x/2-2 @ x=1.5;
>> x = 1.5
>> x^3+2*x^2+x/2-2
===================================================================
Elementary Functions
>>help elfun
Example:
>> sqrt(3)+abs(-4)+exp(2)
===================================================================
Conditional Control: if, else
>>A=5; B=3;
>>if A > B
’greater’
elseif A < B
’less’
elseif A == B
’equal’
else
error(’Unexpected situation’)
end
>>
===================================================================
Loop Control: for, while
2
The "for" loop repeats a group of statements a fixed, predetermined
number of times. A matching "end" delineates the statements:
===================================================================
Example:
Implement the Fibonacii sequence: F(n)=F(n-1)+F(n-2),
F(1)=F(2)=1; Show F(n) for n=1,2,..., 20
for n = 3 : 20
F=F1+F2;
disp([’n=’ num2str(n) ’; F(’ num2str(n) ’)=’ num2str(F)]);
F1=F2;
F2=F;
end
3
n=3;
while n <= 20
F=F1+F2;
disp([’n=’ num2str(n) ’; F(’ num2str(n) ’)=’ num2str(F)]);
F1=F2;
F2=F;
n=n+1;
end