Core MATLAB Syntax
MATLAB primarily utilizes .m files for script execution. The development environment features workspace (left), editor (right), and output (bottom-right) panes.
Basic Input and Output
radius = input('Enter circle radius: ');
area = pi * radius^2;
fprintf('Area = %.2f\n', area);
This script calculates circle area using input() for user data entry and fprintf() for formatted output.
Funciton Definition
function area = computeCircleArea(radius)
% COMPUTECIRCLEAREA Calculate circle area
% computeCircleArea.m
area = pi * radius^2;
end
MATLAB uses percent sign (%) for comments. Functions can return computed values.
Multiple Return Values
function [arithmeticMean, geometricMean] = computeAverages(x, y)
% COMPUTEAVERAGES Calculate arithmetic and geometric means
arithmeticMean = (x + y)/2;
geometricMean = sqrt(x * y);
end
Matrix Operations
frequencies = [1, 2];
voltageSources = [10, 0];
currentSources = [0, 5];
impedance1 = 1./(0.5 * frequencies * 1j);
impedance2 = [2, 2];
impedance3 = [2, 2];
impedance4 = 1 * frequencies * 1j;
openCircuitVoltage = (impedance2 ./ (impedance1 + impedance2) - ...
impedance4 ./ (impedance3 + impedance4)) .* voltageSources;
equivalentImpedance = impedance3 .* impedance4 ./ (impedance3 + impedance4) + ...
impedance1 .* impedance2 ./ (impedance1 + impedance2);
totalVoltage = currentSources .* equivalentImpedance + openCircuitVoltage;
disp('Frequency | Magnitude | Phase (deg)');
disp([frequencies', abs(totalVoltage'), angle(totalVoltage') * 180/pi]);
All MATLAB data exists as matrices. Element-wise operations require dot operator (.). Omitting semicolons (;) displays results.
Conditional Plotting
[X, Y] = meshgrid(-3:0.1:3);
sumXY = X + Y;
Z = zeros(size(X));
Z(sumXY > 1) = 0.54 * exp(-0.75*X(sumXY > 1).^2 - 3.75*Y(sumXY > 1).^2 - 1.5*Y(sumXY > 1));
Z(sumXY <= 1 & sumXY > -1) = 0.7575 * exp(-X(sumXY <= 1 & sumXY > -1).^2 - 6*Y(sumXY <= 1 & sumXY > -1).^2);
Z(sumXY <= -1) = 0.5457 * exp(-0.75*X(sumXY <= -1).^2 - 3.75*Y(sumXY <= -1).^2 + 1.5*Y(sumXY <= -1));
surf(X, Y, Z);
% Alternative plotting functions: plot3, mesh
Surface Visualization
x = linspace(-4, 4, 41);
y = x;
[X, Y] = meshgrid(x, y);
Z = X.^2 + Y.^2;
surf(X, Y, Z);
title('Elliptic Paraboloid Surface');
colormap([0 0 1]); % Blue color mapping
hold on;
for k = -4:0.2:4
for h = -4:0.2:4
plot3(k, h, k^2 + h^2, 'b*', 'MarkerSize', 5);
end
end
Use hold on to overlay multiple plots. linspace generates evenly spaced vectors.
Trigonometric Function Plotting
values = 1:0.1:100;
results = {sin(values), cos(sin(values)), tan(cos(sin(values)))};
hold on;
for i = 1:length(results)
plot(values, results{i});
end
Clear workspace variables with clear before execution to prevent naming conflicts.
Common MATLAB Functionalities
Primary student uses include matrix computations and data visualization. Matrix operations follow linear algebra rules, while plotting functions offer extensive customization through documentation references.