Lecture 3
Lecture 3
== Equal to A == B
~= Not equal to A ~= B
a = 5;
b = 3;
result = (a > b); % Returns true (1)
disp(result); % Output: 1
x = [1, 5, 3];
y = [2, 5, 1];
result = (x == y); % Returns [0, 1, 0]
disp(result); % Output: [0 1 0]
Example 3: Matrix Comparison
A = [1 2; 3 4];
B = [1 0; 3 5];
result = (A >= B); % Returns [1 1; 1 0]
disp(result);
MATLAB supports logical operators (& (AND), | (OR), ~ (NOT)) to combine multiple conditions.
x = 10;
condition = (x > 5) & (x < 15); % true (1)
disp(condition); % Output: 1
a = 7;
b = 10;
result = ~(a == b); % true (1)
disp(result); % Output: 1
A = [1, 2, 3];
B = [2, 2, 2];
result = (A <= B); % [1, 1, 0]
Extra Examples:
MATLAB code segment that generates a random vector of size 20 and performs various filtering
operations, finding:
disp('Original Vector:');
disp(vec);
%% 3. Positive Numbers
positive_nums = vec(vec > 0);
disp('Positive Numbers:');
disp(positive_nums);
%% 4. Even Numbers
even_nums = vec(mod(vec, 2) == 0);
disp('Even Numbers:');
disp(even_nums);
%% 6. Non-Zero Numbers
non_zero_nums = vec(vec ~= 0);
disp('Non-Zero Numbers:');
disp(non_zero_nums);
% 8. Negative Numbers
negative_nums = vec(vec < 0);
disp('Negative Numbers:');
disp(negative_nums);
% 9. Numbers Divisible by 3
divisible_by_3 = vec(mod(vec, 3) == 0);
disp('Numbers Divisible by 3:');
disp(divisible_by_3);
Explanation:
Purpose: Creates a 1×10 row vector of random integers between 1 and 50.
arr_1 = randi(50,[1 10])
Logical Conditions:
o ar = [7, 15]
odd_no=arr_1(mod(arr_1,2)~=0)
Extracts odd numbers from arr_1.
Condition: mod(arr_1, 2) ~= 0 → [1, 0, 1, 1, 0, 1, 0, 1, 0, 1]
Result (odd_no): odd_no = [7, 15, 3, 11, 29, 17]
com=[odd_no, even_no]
Combines odd_no (from arr_1) and even_no (from arr_2) into a single array.
• Example:
nm=[arr_1(mod(arr_1,2)~=0),arr_2(mod(arr_2,2)==0)]
Does the same as com but without intermediate variables.
• Example:
o Rows 1, 4, and 7
o Columns 2, 4, and 7
• Example:
o If A is:
3 14 8 19 2 11 7 15 9 12
17 5 12 6 18 10 16 4 13 1
19 7 1 11 5 14 3 20 8 10
6 16 10 4 12 9 15 2 17 18
11 2 18 8 7 13 5 12 14 6
4 9 3 17 10 20 1 19 15 7
20 1 13 5 16 6 12 8 4 11
• Purpose: Finds the maximum value in each row (dimension 2), along with its column index.
• Outputs:
• Example:
M = [19, 18, 20, 18, 18, 20, 20]
idx = [4, 5, 8, 9, 3, 6, 1]