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

AreaFunction
Command WindowExecute code directly.
WorkspaceView and manage variables.
Current FolderFile directory for scripts.
EditorWrite .m scripts and functions.
Figure WindowDisplays plots.
Help BrowserDocumentation and examples.

Prompt symbol: >>
Comment: %
Suppress output: ;
Continue line: ...


๐Ÿ”น Core Commands

CommandDescription
clcClears the Command Window.
clearRemoves variables from workspace.
clfClears the current figure.
whoLists variable names.
whosLists variables with details.
save filenameSaves workspace to a .mat file.
load filenameLoads a .mat file.
exit / quitCloses MATLAB.
help <function>Displays documentation for a function.
lookfor <keyword>Searches function names and descriptions.
demoOpens built-in demonstrations.
verShows 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

CommandDescription
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

OperationSymbolExample
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

FunctionDescription
abs(x)Absolute value.
sqrt(x)Square root.
sin, cos, tanTrigonometric functions.
asin, acos, atanInverse 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

CommandDescription
disp(x)Quick print.
fprintf()Formatted print.
format short/longControl decimal output.
format compactReduce 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

CommandAxis Type
plotlinear-linear.
semilogxlog-linear.
semilogylinear-log.
logloglog-log.

๐Ÿ”น Specialized Plots

TypeCommand
Barbar(x,y)
Horizontal Barbarh(x,y)
Stemstem(x,y)
Stairsstairs(x,y)
Piepie(x) / pie3(x)
Compasscompass(u,v)
Polarpolarplot(theta,r)
Dual Y-Axisyyaxis left/right

๐Ÿ”น Line Styles & Markers

PropertyExample
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

ConceptFormula / Command
Circle AreaA = ฯ€r^2
CircumferenceC = 2ฯ€r
Simple InterestSI = PRT/100
Temp ConversionF = 9/5*C + 32
BMIweight / height^2
Meanmean(x)
Standard Deviationstd(x)
Roots of Polyroots(coeff)
Poly from rootspoly(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 end or ).
    • Runtime: invalid index, division by zero.
    • Logic: incorrect calculation.

๐Ÿง  Helpful Tips

  • Use ; to suppress output.
  • Use format long for increased decimal precision.
  • Always check vector and matrix sizes before multiplying.
  • Comment often with %.
  • Preallocate arrays for loops (improves speed).
  • Use help anytime 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?