Lab 2
Lab 2
Lab 2:
“Learning, writing mathematical expressions, familiarizing with some more
advanced matlab commands and/or dealing with loops”
Procedure:
Writing mathematical expressions:
MATLAB is an excellent tool for performing mathematical operations and calculations. To write
mathematical expressions in MATLAB, one must become familiar with its syntax and operators.
Some of the commonly used operators are +, -, *, /, ^ (exponent), and sqrt (square root).
For example, to calculate the square root of x, one could write:
sqrt(x)
To calculate the value of sin(x), one could write:
sin(x)
To calculate the sum of two variables, x and y, one could write:
x+y
A = [1, 2, 3, 4, 5];
% Square the array element-wise
B = A .^ 2;
% Display the result
disp('Squared array:');
disp(B);
Explanation:
The .^ operator performs element-wise exponentiation.
disp is used to display the squared array.
While Loop
Alternatively, to perform a calculation until a certain condition is met, one could write:
% Initialize a counter
n = 1;
% Define the stopping condition
while n <= 5
fprintf('Iteration %d\n', n);
% Increment the counter
n = n + 1;
end
Explanation:
The loop runs as long as n <= 5.
The counter n is incremented in each iteration to avoid an infinite loop
fprintf: This function prints text to the command window.
Iteration: A plain text string that gets printed as is.
%d: A placeholder for an integer value. It gets replaced by n in each loop iteration.
\n: A newline character, which moves the cursor to the next line after printing.
n: This specifies that n should replace %d in the format string.