Cpe 104 Note

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

INTRODUCTION TO PROGRAMMING IN MATLAB

In this module, we shall be observing Matlab as a programming language


1. MATLAB as a programming language is a high-level language created especially for scientific
and numerical computation. It offers a wide range of integrated features and resources for algorithm
development, data analysis, and visualization.
2. MATLAB Environment: The MATLAB command window appears when you first open
MATLAB. You can type in and carry out commands here. Moreover, MATLAB comes with an
integrated development environment (IDE) called the MATLAB Editor, which has file
management, debugging, and syntax highlighting capabilities.
3. Variables and Fundamental Operations: In MATLAB, variables can be created to store and
manage data. Variable names are case-sensitive. An illustration of setting variables and carrying out
fundamental operations:

% Variable assignment and basic operations


a = 5;
b = 3;
c = a + b; % Addition
d = a * b; % Multiplication
e = sqrt(c); % Square root

4. Array and Matrices: MATLAB is renowned for its robust operations with arrays and matrices. Square brackets ([])
are used to generate matrices and arrays respectively. As an illustration, consider this:

% Arrays and matrices


x = [1, 2, 3, 4, 5]; % Row vector
y = [1; 2; 3; 4; 5]; % Column vector
A = [1, 2, 3; 4, 5, 6; 7, 8, 9]; % Matrix

MATLAB provides many functions and operators to manipulate arrays


and matrices efficiently.
5. Control Flow: MATLAB allows control flow expressions such as
loops (for, while) and conditional statements (if-else). As an
illustration, consider this:

% Control flow
x = 10;
if x > 0
disp('x is positive');
else
disp('x is non-positive');
end

for i = 1:5
disp(i);
end

i = 1;
while i <= 5
disp(i);
i = i + 1;
end

6. Scripts and Functions: To organize your code in MATLAB, you can


write scripts and functions. Code segments that can take inputs
and return outputs are called functions. Scripts are files that
can be executed in their entirety and contain MATLAB commands.

% Function example
function y = square(x)
y = x^2;
end

% Script example
disp('Hello, MATLAB!');

7. Plotting and Visualization: MATLAB offers strong tools for both plotting and data visualization.
Plots of several kinds can be made, their appearances altered, and labels and annotations added.

% Plotting example

x = linspace(0, 2*pi, 100);


y = sin(x);
plot(x, y);
xlabel('x');
ylabel('sin(x)');
title('Sine Function');

Managing workspace in Matlab


The act of managing the workspace in MATLAB allows you to keep
track of variables, clear unnecessary variables, and organize your
workspace efficiently.

The following are the few commands used in managing workspace in Matlab:

1. Viewing Workspace Variables: you can use the whos command to view the variables
currently stored in your workspace . It displays information such as variable names, sizes,
and data types.

2. Clearing Variables: you can use the clear command followed by the variable names to
remove specific variables from the workspace. For example, to clear variables x and y:

clear x y

Note: use the clear command without any arguments to clear all variables from the
workspace:
clear

3. Clearing the Command Window: clc command can be used to clear the contents of the
MATLAB command window to have a clean workspace. This command clears the
command window but doesn't remove variables from the workspace.

4. Saving and Loading Workspace Variables: MATLAB allows saving your workspace
variables to a file and load them back later. To save the variables, you can use the save
command. For example, to save all variables to a file named "myworkspace.mat":

save('myworkspace.mat')

To load the saved variables back into the workspace, you can use the load command:
load('myworkspace.mat')

5. Exporting and Importing Workspace Variables: If you want to


export workspace variables to a different file format, such
as a CSV or Excel file, use MATLAB's data export functions,
such as writematrix, writecell, or writetable. These
functions allow you to export specific variables or the
entire workspace to the desired format.

To import data from external files into your MATLAB workspace, you can use functions
such as readmatrix, readcell, or readtable. These functions allow you to read
data from various file formats and store it as variables in the workspace.

% Exporting variables to a CSV file


data = [1, 2, 3; 4, 5, 6; 7, 8, 9];
writematrix(data, 'data.csv')

% Importing data from a CSV file


importedData = readmatrix('data.csv')

CONTROL STRUCTURE
MATLAB offers two main types of selective statements:
1. if statements: These are used for conditional execution of code
blocks based on whether a certain condition is true or false.

The basic syntax:


if (condition)
statement1
statement2
...
end
“condition” is a logical expression that evaluates to true or
false.
“statement1”, “statement2”, etc. are the code blocks that will be
executed if the `condition` is true.
Optionally, you can add an “else” block to execute code if the
“condition” is false:
if (condition)
statement1
statement2
...
else
statement3
statement4
...
end

You can also use “elseif” for more complex conditions with
multiple possibilities:
if (condition1)
statement1
elseif (condition2)
statement2
else
statement3
end
2. switch statements: These are used for selecting code based on
the value of a variable compared to multiple cases.

the basic syntax:


switch variable
case value1
statement1
statement2
...
case value2
statement3
statement4
...
otherwise
statement5
statement6
...
end
“variable” is the value being compared.
“case value1”, “case value2”, etc. are the cases to be checked.
The code block associated with the first matching case is
executed.

“otherwise” is an optional block that executes if none of the


cases match.

Note: Remember to use proper indentation to distinguish code


blocks within these statements.

Examples:
1. if statement with “else”:

grade = 85; // initialization


if grade >= 90
disp('Excellent!')
else
disp('Good job, but you can do better.')
end
This example checks the value of “grade”. If it's 90 or above, it
displays "Excellent!". Otherwise, it displays 'Good job, but you
can do better.'.

2. if statement with elseif:


number = -2; // Initialization
if number > 0
disp('The number is positive.')
elseif number < 0
disp('The number is negative.')
else
disp('The number is zero.')
end
This example checks the value of “number”. It displays a message
depending on whether the number is positive, negative, or zero.

3. switch statement:
day = 'Tuesday';// initialization
switch day
case 'Monday'
disp('Start of the work week.')
case 'Tuesday'
disp('Just another workday.')
case 'Wednesday'
disp('Hump day!')
otherwise
disp('It's the weekend!')
end
This example checks the value of the string variable “day”.
Depending on the day, it displays a corresponding message.

You might also like