Cpe 104 Note
Cpe 104 Note
Cpe 104 Note
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:
% 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
% 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
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')
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.
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.
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.
Examples:
1. if statement with “else”:
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.