MATLAB Basics: Environment, Commands, Plotting & Tips
๐ฅ๏ธ 1. MATLAB Basics & Environment
MATLAB = Matrix Laboratory โ a numerical computing environment and programming language built for engineering and mathematical operations.
๐น Interface Overview
| Area | Function |
|---|---|
| Command Window | Execute code directly. |
| Workspace | View and manage variables. |
| Current Folder | File directory for scripts. |
| Editor | Write .m scripts and functions. |
| Figure Window | Displays plots. |
| Help Browser | Documentation and examples. |
Prompt symbol: >>
Comment: %
Suppress output: ;
Continue line: ...
๐น Core Commands
| Command | Description |
|---|---|
clc | Clears the Command Window. |
clear | Removes variables from workspace. |
clf | Clears the current figure. |
who | Lists variable names. |
whos | Lists variables with details. |
save filename | Saves workspace to a .mat file. |
load filename | Loads a .mat file. |
exit / quit | Closes MATLAB. |
help <function> | Displays documentation for a function. |
lookfor <keyword> | Searches function names and descriptions. |
demo | Opens built-in demonstrations. |
ver | Shows version information. |
๐น Scripting & Execution
Script: a series of commands saved in a .m file.
Run by typing the filename (without .m).
Example Script:
% Circle area calculation
r = 5;
A = pi * r^2;
fprintf('Area = %.2f\n', A)
๐งฉ 2. Variables, Arrays & Operations
๐น Variable Rules
- Must start with a letter.
- Case sensitive.
- Cannot contain spaces.
- Assign using
=.
Examples:
x = 5;
y = 3.14;
z = 'hello';
๐น Arrays & Matrices
Row vector: v = [1 2 3 4]
Column vector: v = [1; 2; 3; 4]
Matrix:
A = [1 2 3;
4 5 6;
7 8 9];
๐น Array Generation Functions
| Command | Description |
|---|---|
zeros(m,n) | mรn array of zeros. |
ones(m,n) | mรn array of ones. |
rand(m,n) | Random numbers in (0โ1). |
eye(n) | nรn identity matrix. |
diag(v) | Creates a diagonal matrix. |
linspace(a,b,n) | n equally spaced points. |
reshape(v,m,n) | Reshapes vector to mรn. |
length(v) | Number of elements in a vector. |
size(A) | Matrix dimensions. |
numel(A) | Total number of elements. |
๐น Colon Operator
Creates ranges:
v = 1:2:10 % [1 3 5 7 9]
Row โ column: v'
Every k-th element: v(1:3:end)
Example (Lab 2):
v = 5:5:50; % row vector
v = v'; % column vector
v(1:3:end)
๐น Subarrays & Indexing
A(r1:r2, c1:c2) extracts a submatrix.
A(:,2) โ entire 2nd column.
A(3,:) โ entire 3rd row.
A(2,:) = 0 โ replace row with zeros.
end keyword = last index.
Example (Lab 2):
B = [2 4 6 8;
1 3 5 7;
9 11 13 15];
B(:, [1 end]) % first and last columns
B(2,:) = 0;
๐น Arithmetic Operators
| Operation | Symbol | Example |
|---|---|---|
| Addition | + | A+B |
| Subtraction | - | A-B |
| Multiplication | * | Matrix multiply. |
| Division | / | Matrix divide. |
| Power | ^ | Exponentiation. |
| Elementwise multiply | .* | Same-size arrays. |
| Elementwise divide | ./ | Same-size arrays. |
| Elementwise power | .^ | Same-size arrays. |
Order of operations:
() โ ^ โ *// โ +/-.
๐น Built-in Math Functions
| Function | Description |
|---|---|
abs(x) | Absolute value. |
sqrt(x) | Square root. |
sin, cos, tan | Trigonometric functions. |
asin, acos, atan | Inverse trig functions. |
exp(x) | e^x. |
log(x) | Natural logarithm. |
log10(x) | Base-10 logarithm. |
rem(x,y) | Remainder. |
mod(x,y) | Modulus. |
sum(x) | Sum of elements. |
mean(x) | Average. |
median(x) | Median. |
std(x) | Standard deviation. |
[m,i]=max(A) | Maximum value and index. |
[n,j]=min(A) | Minimum value and index. |
๐น Display & Formatting
| Command | Description |
|---|---|
disp(x) | Quick print. |
fprintf() | Formatted print. |
format short/long | Control decimal output. |
format compact | Reduce spacing in output. |
Example (Lab 2):
temp = 37.4567;
disp(temp)
fprintf('The temperature is %.1fยฐC\n', temp)
๐น Special Constants
pi, i/j, Inf, NaN, eps, date, clock, ans.
Example (Lab 2):
1/0 % Inf
Inf-Inf % NaN
๐ 3. Plotting & Visualization
๐น Basic Plotting
x = 0:0.1:10;
y = sin(x);
plot(x,y,'r--o','LineWidth',1.5)
xlabel('x'); ylabel('sin(x)');
title('Sine Wave'); grid on
Multiple plots:
hold on
plot(x,cos(x),'b')
legend('sin(x)','cos(x)')
hold off
Axis commands:
axis equal, axis tight, axis square, axis off.
Subplots:
subplot(2,1,1); plot(x,sin(x));
subplot(2,1,2); plot(x,cos(x));
sgtitle('Sine vs Cosine')
๐น Logarithmic Plots
| Command | Axis Type |
|---|---|
plot | linear-linear. |
semilogx | log-linear. |
semilogy | linear-log. |
loglog | log-log. |
๐น Specialized Plots
| Type | Command |
|---|---|
| Bar | bar(x,y) |
| Horizontal Bar | barh(x,y) |
| Stem | stem(x,y) |
| Stairs | stairs(x,y) |
| Pie | pie(x) / pie3(x) |
| Compass | compass(u,v) |
| Polar | polarplot(theta,r) |
| Dual Y-Axis | yyaxis left/right |
๐น Line Styles & Markers
| Property | Example |
|---|---|
| Color | 'r', 'b', 'g', 'k' |
| Style | '-', '--', ':', '-.' |
| Marker | 'o', 'x', 's', 'd', '*' |
| Width | 'LineWidth',2 |
| Marker Size | 'MarkerSize',8 |
๐น Annotating Plots
text(12,25,'Midday Peak')
annotation('textbox',[.5 .5 .1 .1],'String','Note')
๐น Lab Examples
Lab 3 โ Weather Dashboard:
t=0:1:24;
T=18+7*sin(pi*(t-6)/12);
H=60+15*cos(pi*t/12);
yyaxis left; plot(t,T,'r--o');
yyaxis right; plot(t,H,'b');
title('Daily Weather'); grid on
Lab 3 โ Elevator Motion:
stairs(tStops,floors);
hold on; stem(tStops,floors);
bar(floors(2:end),dwell);
Lab 3 โ Wind Snapshot:
theta=dirDeg*pi/180;
polarplot(theta,spd,'o-');
u=spd.*cos(theta); v=spd.*sin(theta);
compass(u,v);
โ๏ธ 4. Logicals, Branching & Design
๐น Relational Operators
==, ~=, <, >, <=, >=.
๐น Logical Operators
&, |, ~, &&, ||, xor(a,b).
๐น if / elseif / else
if temp>35
disp('Too hot')
elseif temp<15
disp('Too cold')
else
disp('Safe')
end
๐น switch / case
switch choice
case 1, A=pi*r^2;
case 2, A=L*W;
case 3, A=0.5*b*h;
otherwise, disp('Invalid')
end
๐น try / catch
try
riskyOp
catch
disp('Error handled')
end
๐น Lab Examples
Lab 4 โ Temperature Safety:
temp = input('Enter temperature: ');
if (temp>=15)&&(temp<=35)
disp('Safe to operate')
elseif temp<15
disp('Too cold')
else
disp('Too hot')
end
Lab 4 โ Grading System:
score=input('Enter score: ');
if score>=90
disp('A')
elseif score>=80
disp('B')
elseif score>=70
disp('C')
elseif score>=60
disp('D')
else
disp('F')
end
๐ 5. Loops & Iteration
๐น while-loop
temp=51; t=0;
while temp>35 && t<120
fprintf('t=%d min: %.1fยฐC\n',t,temp)
temp=temp-3.5; t=t+1;
end
if temp<=35
disp('SAFE')
else
disp('ALERT')
end
๐น for-loop
steps=[5600 7200 6800 8000 9100 4500 10200];
total=0; maxSteps=0;
for i=1:length(steps)
total=total+steps(i);
if steps(i)>maxSteps
maxSteps=steps(i); day=i;
end
end
avg=total/length(steps);
fprintf('Total=%d Avg=%.1f MaxDay=%d\n',total,avg,day)
๐น continue / break
tx=[45 52 -1 39 99999 28];
sum=0;
for k=1:length(tx)
if tx(k)<0, fprintf('Skip %d\n',tx(k)); continue; end
if tx(k)==99999, fprintf('FRAUD FLAG at %d\n',k); break; end
sum=sum+tx(k);
end
๐งฎ 6. Functions
๐น Basic Function Structure
function out = funcName(inputs)
% Description (H1 line)
out = expression;
end
๐น Example (Lab 6)
function Rt = series_resistance(R1,R2)
Rt = R1 + R2;
end
๐น Pass-by-Value
Variables inside functions do not affect originals outside.
๐น Optional Inputs / Outputs
function [avg,stdev]=temp_analysis(data,unit)
narginchk(1,2)
if nargin==1, unit='C'; end
if unit=='F', data=(data-32)*5/9; end
if ~isnumeric(data), error('Must be numeric'); end
avg=mean(data);
if nargout>1, stdev=std(data); end
end
๐น Persistent Variable
function total = alert_counter(value)
persistent count
if isempty(count), count=0; end
if nargin==0, total=count; return; end
if ischar(value)&&strcmp(value,'reset')
count=0;
else
count=count+value;
end
total=count;
end
โก 7. Formulas, Shortcuts, and Hints
| Concept | Formula / Command |
|---|---|
| Circle Area | A = ฯr^2 |
| Circumference | C = 2ฯr |
| Simple Interest | SI = PRT/100 |
| Temp Conversion | F = 9/5*C + 32 |
| BMI | weight / height^2 |
| Mean | mean(x) |
| Standard Deviation | std(x) |
| Roots of Poly | roots(coeff) |
| Poly from roots | poly(r) |
โ๏ธ Debugging
- Breakpoints: click the red dot in the Editor.
- Step In/Over/Out: trace code execution.
- Pause on Errors: automatically stop on errors.
- Common Errors:
- Syntax: missing
endor). - Runtime: invalid index, division by zero.
- Logic: incorrect calculation.
- Syntax: missing
๐ง Helpful Tips
- Use
;to suppress output. - Use
format longfor increased decimal precision. - Always check vector and matrix sizes before multiplying.
- Comment often with
%. - Preallocate arrays for loops (improves speed).
- Use
helpanytime for documentation.
Would you like me to continue this reference to include:
More lab-specific โExpected Answerโ outputs and formulas
Extra notes on function handles, input/output, debugging tools, and plotting formatting (color, grid, axis labels, etc.)
It would add another 4โ5 pages worth of information, still as text.
Do you want me to keep going?
