MATLAB Problems and Solutions for Job Seekers
MATLAB is an extremely powerful tool for scientists and engineers, providing a strong environment for visualization, numerical computation, and programming. This tutorial provides a set of problems and solutions aimed at getting you proficient with fundamental MATLAB concepts, ranging from syntax to advanced algorithms. You’ll discover how to solve real-world problems effectively. Ready to advance your skills? Explore our MATLAB course syllabus.
MATLAB Problems and Solutions
Here are the main MATLAB Problems and Solutions:
Signal Processing and Filtering
Problem: A noisy signal is provided by the equation y(t)=0.5
sin(2
pi
cdot5t)+
cos(2
pi
cdot50t)+0.5
sin(2
pi
cdot200t),
where the last two terms represent noise. The signal is sampled at 1000 Hz for 1 second. Remove the noise and filter out the desired 5 Hz sine wave with a low-pass filter.
Solution:
We’ll remove high-frequency noise by using a Butterworth low-pass filter. Design of the filter is essential to separate the 5 Hz signal.
Sample Code: MATLAB
% Given parameters
fs = 1000; % Sampling frequency (Hz)
t = 0:1/fs:1-1/fs; % Time vector
y_noisy = 0.5*sin(2*pi*5*t) + cos(2*pi*50*t) + 0.5*sin(2*pi*200*t); % Noisy signal
% Design a low-pass Butterworth filter
fc = 10; % Cutoff frequency (Hz)
[b, a] = butter(6, fc/(fs/2), ‘low’); % 6th order Butterworth filter
% Apply the filter
y_filtered = filter(b, a, y_noisy);
% Plot the signals
figure;
plot(t, y_noisy, ‘b’, ‘DisplayName’, ‘Noisy Signal’);
hold on;
plot(t, y_filtered, ‘r’, ‘LineWidth’, 2, ‘DisplayName’, ‘Filtered Signal’);
xlabel(‘Time (s)’);
ylabel(‘Amplitude’);
title(‘Signal Filtering’);
legend;
grid on;
Image Processing and Edge Detection
Problem: Load a grayscale image and use a Canny edge detector to emphasize its edges. This is a basic operation in computer vision tasks such as object recognition.
Solution:
The edge function of MATLAB offers several options for detecting edges. The ‘Canny’ option is the best since it’s less affected by noise.
Code Sample: MATLAB
% Load an example image
img = imread(‘cameraman.tif’);
% Convert the image to grayscale if it’s not already
if size(img, 3) == 3
img_gray = rgb2gray(img);
else
img_gray = img;
end
% Apply the Canny edge detector
edges = edge(img_gray, ‘canny’);
% Display the original and edge-detected images
figure;
subplot(1, 2, 1);
imshow(img_gray);
title(‘Original Grayscale Image’);
subplot(1, 2, 2);
imshow(edges);
title(‘Canny Edge Detection’);
Recommended: MATLAB Course Online.
Data Analysis and Regression
Problem: For a given set of independent variable x and dependent variable y, determine the best-fit linear regression line. Plot the data and the regression line.
Solution:
We can utilize the built-in functions in MATLAB to do linear regression. The polyfit function returns the coefficients for the polynomial, and polyval calculates the polynomial at a given set of points.
% Sample data
x = [1, 2, 3, 4, 5, 6, 7];
y = [2.5, 4.2, 5.1, 7.3, 9.5, 11.0, 12.8];
% Perform linear regression (degree 1 polynomial)
coefficients = polyfit(x, y, 1);
m = coefficients(1); % Slope
c = coefficients(2); % Y-intercept
% Create the regression line
y_fit = polyval(coefficients, x);
% Plot the original data and the regression line
figure;
scatter(x, y, ‘filled’, ‘DisplayName’, ‘Original Data’);
hold on;
plot(x, y_fit, ‘r’, ‘LineWidth’, 2, ‘DisplayName’, [‘Regression Line: y = ‘ num2str(m, ‘%.2f’) ‘x + ‘ num2str(c, ‘%.2f’)]);
xlabel(‘Independent Variable (x)’);
ylabel(‘Dependent Variable (y)’);
title(‘Linear Regression’);
legend;
grid on;
Control Systems and Transfer Functions
Problem: A control system is characterized by the transfer function G(s)=frac2s+1s2+5s+6. Find the step response of the system.
Solution:
Transfer functions are made easy to analyze using the Control System Toolbox in MATLAB. We specify the transfer function and subsequently use the step command to determine its step response.
Code Sample: MATLAB
% Define the numerator and denominator polynomials of the transfer function
num = [2 1];
den = [1 5 6];
% Create the transfer function object
sys = tf(num, den);
% Find and plot the step response
figure;
step(sys);
title(‘Step Response of the Control System’);
grid on;
Recommended: MATLAB Tutorial for Beginners.
Financial Modeling and Monte Carlo Simulation
Problem: Estimate the price of a stock over a year using a Geometric Brownian Motion (GBM) model. The initial price of the stock is S_0, with an annual drift
mu and volatility
sigma.
Solution:
GBM is a popular model for asset prices. A Monte Carlo simulation consists of creating many random paths to estimate the distribution of future prices.
Code Sample:
% Parameters for the simulation
S0 = 100; % Initial stock price
mu = 0.05; % Annual drift
sigma = 0.2; % Annual volatility
T = 1; % Time horizon (1 year)
N = 252; % Number of trading days in a year
dt = T/N; % Time step
num_simulations = 1000; % Number of simulation paths
% Pre-allocate a matrix to store the simulation paths
S = zeros(N, num_simulations);
S(1, 🙂 = S0;
% Perform the Monte Carlo simulation
for i = 1:num_simulations
for j = 2:N
% Generate a random number from a standard normal distribution
dW = sqrt(dt) * randn;
% Apply the GBM formula
S(j, i) = S(j-1, i) * exp((mu – 0.5*sigma^2)*dt + sigma*dW);
end
end
% Plot a few sample paths
figure;
plot(S(:, 1:10)); % Plot the first 10 paths
xlabel(‘Time Step (Days)’);
ylabel(‘Stock Price’);
title(‘Monte Carlo Simulation of Stock Price’);
grid on;
Robotics and Kinematics
Problem: A two-link robot arm with link lengths L_1 and L_2 has joint angles theta_1 and theta_2. Find the end-effector position (x, y) through forward kinematics.
Solution:
Forward kinematics is the computation of the end position of a kinematic chain from its joint angles. We will use trigonometry to solve it.
Code Sample:
% Given link lengths and joint angles
L1 = 1.5; % Length of the first link (m)
L2 = 1.0; % Length of the second link (m)
theta1 = 30; % Joint 1 angle (degrees)
theta2 = -45; % Joint 2 angle (degrees)
% Convert angles to radians
theta1_rad = deg2rad(theta1);
theta2_rad = deg2rad(theta2);
% Calculate the position of the first joint
x1 = L1 * cos(theta1_rad);
y1 = L1 * sin(theta1_rad);
% Calculate the end-effector position
x_effector = x1 + L2 * cos(theta1_rad + theta2_rad);
y_effector = y1 + L2 * sin(theta1_rad + theta2_rad);
% Display the results
fprintf(‘End-effector position: (%.2f, %.2f) meters\n’, x_effector, y_effector);
% Optional: Plot the robot arm
figure;
plot([0, x1, x_effector], [0, y1, y_effector], ‘b-o’, ‘LineWidth’, 2, ‘MarkerSize’, 8);
hold on;
scatter([0, x1], [0, y1], ‘r’, ‘filled’);
xlabel(‘X Position (m)’);
ylabel(‘Y Position (m)’);
title(‘2-DOF Robot Arm Forward Kinematics’);
grid on;
axis equal;
Recommended: MATLAB Interview Questions and Answers.
Biomedical Signal Processing (ECG Analysis)
Problem: Load a test ECG signal, locate the QRS complexes, and compute the heart rate. It is a general task in medical device software.
Solution:
We will use a pan-tompkins algorithm to locate the R-peaks, which are equivalent to the QRS complexes. The problem can be reduced using signal processing functions for finding local maxima and peaks.
% A simple simulated ECG signal
fs = 200; % Sampling rate
t = 0:1/fs:10;
heart_rate_bpm = 70;
period = 60/heart_rate_bpm;
num_beats = floor(t(end)/period);
ecg_signal = zeros(size(t));
for i = 1:num_beats
peak_time = i * period;
% Create a “QRS complex” with a Gaussian shape
ecg_signal = ecg_signal + 0.8 * exp(-((t – peak_time).^2) / (0.01^2));
% Add P and T waves
ecg_signal = ecg_signal + 0.3 * exp(-((t – (peak_time – 0.2)).^2) / (0.02^2)); % P wave
ecg_signal = ecg_signal + 0.4 * exp(-((t – (peak_time + 0.3)).^2) / (0.03^2)); % T wave
end
% Find peaks (R-peaks)
[pks, locs] = findpeaks(ecg_signal, ‘MinPeakHeight’, 0.5);
% Calculate heart rate
if length(locs) > 1
% Calculate average time between R-peaks
avg_R_R_interval_sec = mean(diff(locs)) / fs;
% Calculate heart rate in beats per minute (BPM)
heart_rate = 60 / avg_R_R_interval_sec;
fprintf(‘Estimated Heart Rate: %.2f BPM\n’, heart_rate);
else
fprintf(‘Could not detect enough R-peaks.\n’);
end
% Plot the ECG signal and detected peaks
figure;
plot(t, ecg_signal);
hold on;
plot(t(locs), pks, ‘ro’, ‘MarkerFaceColor’, ‘r’);
title(‘ECG Signal Analysis’);
xlabel(‘Time (s)’);
ylabel(‘Amplitude (mV)’);
legend(‘ECG Signal’, ‘R-Peaks’);
grid on;
Optimization and Non-Linear Equations
Problem: Determine the minimum of the Rosenbrock function, a traditional optimization test problem, given by f(x,y)=(1−x)2+100(y−x2)2.
Solution:
The Optimization Toolbox in MATLAB offers robust solvers such as fminunc (for unconstrained minimization) to determine the minimum of a function.
Code Sample:
% Define the Rosenbrock function as an anonymous function
rosenbrock = @(x) (1-x(1))^2 + 100*(x(2)-x(1)^2)^2;
% Set a starting point
x0 = [-1, 1];
% Find the minimum using fminunc
[x_min, f_min] = fminunc(rosenbrock, x0);
% Display the results
fprintf(‘Minimum of the function found at (%.4f, %.4f)\n’, x_min(1), x_min(2));
fprintf(‘Minimum function value: %.4f\n’, f_min);
% The true minimum is at (1, 1) with a value of 0.
Recommended: MATLAB Course in OMR.
Communication Systems and Modulation
Problem: Use Amplitude Shift Keying (ASK) to modulate a simple sine wave signal. Display the original carrier, modulating signal, and the output after modulation.
Solution:
ASK is a modulation scheme that is digital. The amplitude of a carrier signal is modulated to encode digital data. We will use a simple square wave for the digital signal here.
Code Sample:
% System parameters
fs = 1000; % Sampling frequency
fc = 100; % Carrier frequency
fm = 10; % Message frequency
t = 0:1/fs:1-1/fs; % Time vector
% Generate the carrier signal
carrier = sin(2*pi*fc*t);
% Generate the modulating signal (a simple square wave)
mod_signal = square(2*pi*fm*t);
% Convert to a binary-like signal (0 or 1)
mod_signal(mod_signal < 0) = 0;
% Perform ASK modulation
ask_signal = (1 + mod_signal) .* carrier;
% Plot the signals
figure;
subplot(3, 1, 1);
plot(t, carrier);
title(‘Carrier Signal’);
xlabel(‘Time (s)’);
ylabel(‘Amplitude’);
ylim([-1.2, 1.2]);
grid on;
subplot(3, 1, 2);
plot(t, mod_signal);
title(‘Modulating Signal’);
xlabel(‘Time (s)’);
ylabel(‘Amplitude’);
ylim([-0.2, 1.2]);
grid on;
subplot(3, 1, 3);
plot(t, ask_signal);
title(‘ASK Modulated Signal’);
xlabel(‘Time (s)’);
ylabel(‘Amplitude’);
ylim([-2.2, 2.2]);
grid on;
% Add a space between subplots for better visualization
linkaxes([subplot(3, 1, 1), subplot(3, 1, 2), subplot(3, 1, 3)], ‘x’);
Machine Learning and Data Classification
Problem: Classify new data points using a k-Nearest Neighbors (k-NN) algorithm from a training dataset. This is an essential supervised learning problem.
Solution:
Statistics and Machine Learning Toolbox contains routines such as fitcknn to train k-NN and predict to perform prediction. We will utilize a simple, artificially generated dataset for this purpose.
% Generate a simple 2D training dataset
rng(1); % for reproducibility
train_data = rand(50, 2);
train_labels = (train_data(:, 1) + train_data(:, 2) > 1.2); % A simple classification rule
% Create a new data point to classify
new_point = [0.6, 0.4];
% Train a k-NN classifier model
k = 3; % Number of neighbors to consider
knn_model = fitcknn(train_data, train_labels, ‘NumNeighbors’, k);
% Predict the label for the new data point
predicted_label = predict(knn_model, new_point);
% Display the result
fprintf(‘The new data point (%.2f, %.2f) is classified as: %d\n’, new_point(1), new_point(2), predicted_label);
% Optional: Plot the data and the new point
figure;
gscatter(train_data(:, 1), train_data(:, 2), train_labels, ‘br’, ‘xo’);
hold on;
plot(new_point(1), new_point(2), ‘k*’, ‘MarkerSize’, 12, ‘LineWidth’, 2);
title(‘k-NN Classification’);
xlabel(‘Feature 1’);
ylabel(‘Feature 2’);
legend(‘Class 0’, ‘Class 1’, ‘New Point’);
grid on;
Explore: All Software Training Courses.
Conclusion
With these exercises, we’ve only touched the surface of MATLAB’s capabilities in signal processing, data analysis, and machine learning. From cleaning noisy data to modeling financial systems, MATLAB is a necessary tool for real-world applications. With these skills, you can apply complex engineering and scientific problems. Ready to take your skills to the next level? Join our comprehensive and Best MATLAB course in Chennai to reach your full potential.